【问题标题】:Can I select mysqli db rows using ajax?我可以使用 ajax 选择 mysqli db 行吗?
【发布时间】:2016-12-23 18:01:05
【问题描述】:

我正在 php 中创建一个程序,用户选择一个字母,然后在屏幕上打印所有以该字母开头的名称,这些名称存储在我的 mysql“presta_prova”数据库中。 这是我的代码(php文件):

<!DOCTYPE html>
<html>

<head>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }
    table,
    td,
    th {
      border: 1px solid black;
      padding: 5px;
    }
    th {
      text-align: left;
    }
  </style>
  <script>
    function showUser(str) {
      if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
      } else {
        if (window.XMLHttpRequest) {
          // code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp = new XMLHttpRequest();
        } else {
          // code for IE6, IE5
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
          if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
          }
        };
        xmlhttp.open("GET", "presta_prova.php?q=" + str, true);
        xmlhttp.send();
      }
    }
  </script>
</head>

<body>
  <form>
    <select name="users" onchange="showUser(this.value)">
      <option value="">Scegliete una lettera:</option>
      <option value="1">A</option>
      <option value="2">B</option>
      <option value="3">C</option>
      <option value="4">D</option>
    </select>
  </form>
  <br>
  <div id="txtHint"><b>Vedi qui i tipi ti marche:</b>
  </div>
  <?php $q=i ntval($_GET[ 'q']); $con=m ysqli_connect( 'localhost', 'root', 'evolvia2016', 'presta_prova'); if (!$con) { die( 'Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con, "presta_prova"); $sql="SELECT * FROM presta_prova WHERE marca LIKE '"
  .$q%. "' "; $result=m ysqli_query($con,$sql); echo "<table>
<tr>
<th>Marca</th>
<th>Descrizione</th>
</tr>"; while($row=m ysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row[ "marca"] . "</td>"; echo "<td>" . $row[ "descrizione"] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?>
</body>

</html>
但是当我选择一个字母时,这就是我的输出。而不是我的数据库行,这个程序输出表的头部。我的代码做错了吗?也许这种方式不适用于mysqli数据库?谢谢! 这是我的数据库:

【问题讨论】:

  • 忽略会导致语法错误的随机空格,.$q%. 也会导致语法错误。 %,即通配符需要在 SQL 字符串中。

标签: php ajax database


【解决方案1】:

如果目标是用新行填充表,而不是将响应附加到 div 中,那么您可以重组代码并像这样使用 POST。

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();

        /* Forgot to change this to POST! */
        $q=intval($_POST[ 'q']);

        $con=mysqli_connect( 'localhost', 'root', 'evolvia2016', 'presta_prova');
        if (!$con)die( 'Could not connect: ' . mysqli_error($con));

        mysqli_select_db($con, "presta_prova");
        $sql="SELECT * FROM presta_prova WHERE marca LIKE '".$q."%' ";
        $result=mysqli_query($con,$sql);



        $html=array("<tr><th>Marca</th><th>Descrizione</th></tr>");

        while( $row=mysqli_fetch_array($result) ) { 
            $html[]="<tr><td>" . $row[ "marca"] . "</td><td>" . $row[ "descrizione"] . "</td></tr>"; 
        } 

        mysqli_close($con);


        exit( implode(PHP_EOL,$html) );
    }

?>


<!DOCTYPE html>
<html>
    <head>
    <title>gotta have a title</title>
      <style>
        table {
          width: 100%;
          border-collapse: collapse;
        }
        table,
        td,
        th {
          border: 1px solid black;
          padding: 5px;
        }
        th {
          text-align: left;
        }
      </style>
      <script>
        function showUser(str) {
          if (str == "") {
            document.getElementById("txtHint").innerHTML = "";
            return;
          } else {
            if (window.XMLHttpRequest) {
              // code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp = new XMLHttpRequest();
            } else {
              // code for IE6, IE5
              xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function() {
              if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("results").innerHTML = xmlhttp.responseText;
              }
            };
            xmlhttp.open("POST", location.href, true );/*"presta_prova.php"*/
            /* send the content-type header */
            xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

            /* my mistake here, this should be like this rather than object literal. */
            xmlhttp.send( 'q='+str );

          }
        }
      </script>
    </head>
    <body>
      <form>
        <select name="users" onchange="showUser( this.value )">
          <option value="">Scegliete una lettera:</option>
          <option value="1">A</option>
          <option value="2">B</option>
          <option value="3">C</option>
          <option value="4">D</option>
        </select>
      </form>
      <br>
      <div id="txtHint"><b>Vedi qui i tipi ti marche:</b>
      </div>
      <table id='results'>
        <tr>
            <th>Marca</th>
            <th>Descrizione</th>
        </tr>
        </table>
    </body>
</html>

没有数据库交互但显示选择机制工作的完整工作示例。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        ob_clean();

        $q=intval( $_POST[ 'q'] );
        $t=$_POST['text'];

        /* emulated database search and results being generated */
        $html=array('<tr><th>Marca</th><th>Descrizione</th></tr>');
        for( $i=0; $i < 10; $i++ ) $html[]='<tr><td>Marca:'.$i.' q='.$q.'</td><td>Descrizione:'.$i.' text='.$t.'</td></tr>';

        header( 'Content-Type: text/html' );
        exit( implode( PHP_EOL, $html ) );
    }
?>
<!DOCTYPE html>
<html>
    <head>
    <title>gotta have a title</title>
      <style>
        table {
          width: 100%;
          border-collapse: collapse;
        }
        table,
        td,
        th {
          border: 1px solid black;
          padding: 5px;
        }
        th {
          text-align: left;
        }
      </style>
      <script>
        function showUser(o) {
          if (o.value == '') {
            document.getElementById("txtHint").innerHTML = "";
            return;
          } else {

            xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange = function() {
              if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("results").innerHTML = xmlhttp.responseText;
              }
            };
            xmlhttp.open( "POST", location.href, true );
            xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            xmlhttp.send( 'q='+o.value+'&text='+o.options[o.options.selectedIndex].text );
          }
        }
      </script>
    </head>
    <body>
      <form>
        <select name="users" onchange="showUser( this )">
          <option value="">Scegliete una lettera:</option>

          <?php
            /* Generate each letter of the alphabet as an option */
            for( $i=0; $i<26; $i++ ){
                $char=chr( $i + 65 );
                $int=$i+1;
                echo "<option value='$int'>$char";
            }
          ?>
        </select>
      </form>
      <br>
      <div id="txtHint"><b>Vedi qui i tipi ti marche:</b>
      </div>
      <table id='results'><!-- results will overwrite the table innerHTML -->
        <tr>
            <th>Marca</th>
            <th>Descrizione</th>
        </tr>
       </table>
    </body>
</html>

【讨论】:

  • 好的,这不是交互式的。我选择了一封信,然后什么也没有发生。我不知道这是否适用于您的电脑。
  • 我必须承认在 ajax 请求中发送参数时犯了一个小错误——我认为咖啡还没有开始起作用。当然,它应该是 q=A 等格式的字符串,而不是对象文字 - 还设置 Content-Type 标头。
  • 也许我应该插入一些脚本让它工作?我的本地主机中没有任何内容。
猜你喜欢
  • 1970-01-01
  • 2014-11-25
  • 2014-10-04
  • 1970-01-01
  • 2012-09-26
  • 2021-12-08
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多