在PHP中运行SQL查询时出错

时间:2015-12-15 06:13:39

标签: php sql

我对php很新,并且学习如何使用php运行SQL查询。

到目前为止,我写了以下代码:

    <?php
      $servername="localhost";
      $user="root";
      $password="mypassword";
      $dbname="mydbname";

      //Create Connection
      $conn=mysqli_connect($servername,$user,$password,$dbname);


      //Check connection
      if(!$conn)
        {
            die("connection failed" . mysqli_connect_error());
        }

        echo "<b>Connection is Successfull.</b>";


            mysqli_close($conn);
            unset($conn);
            $sql = "SELECT * FROM users";

            $query=mysqli_query($conn, $sql) or die(mysql_error())

        ?>

当我运行上面的代码时,它会给我以下错误

连接成功。

  

注意:未定义的变量:第34行的/index2.php中的conn

     

警告:mysqli_query()要求参数1为mysqli,在第34行的index2.php中给出null

我尝试了其他几种方法,但都显示出某种错误。

4 个答案:

答案 0 :(得分:0)

在发送查询之前关闭连接。解散:)

移动

mysqli_close($conn);
unset($conn);

以下

$sql = "SELECT * FROM users";
$query=mysqli_query($conn, $sql) or die(mysql_error())

答案 1 :(得分:0)

在执行查询之前,您无法关闭mysqli连接。

执行所有查询时必须关闭连接。

<?php
      $servername="localhost";
      $user="root";
      $password="mypassword";
      $dbname="mydbname";

      //Create Connection
      $conn=mysqli_connect($servername,$user,$password,$dbname);


      //Check connection
      if(!$conn)
        {
            die("connection failed" . mysqli_connect_error());
        }

        echo "<b>Connection is Successfull.</b>";



            $sql = "SELECT * FROM users";

$query=mysqli_query($conn, $sql) or die(mysql_error())
mysqli_close($conn);
            unset($conn);
        ?>

答案 2 :(得分:0)

例如:

//mysql configuration
     $server = "localhost";
     $dbuser = "root";
     $dbpw = "";
     $db = "db";
     $con = "";
     $con = new mysqli($server,$dbuser,$dbpw, $db);
 //get data from table   
        $sql = "SELECT * FROM users";
            $rs=$con->query($sql);
            while($row = $rs->fetch_assoc()){
    echo $row['ID'];
    }

答案 3 :(得分:-1)

$sql = "SELECT * FROM users";
$query=mysqli_query($conn, $sql) or die( mysqli_error($conn));
mysqli_close($conn);
unset($conn);