MySQL数据库连接没问题,但查询不会执行

时间:2015-12-26 08:29:24

标签: php mysql

我有这个PHP代码

<?php
$servername="localhost";
$username="b6_17093244";
$password="password1";
$dbName="b6_17093244_math";
$conn = new mysqli($servername, $username, $password, $dbName);
if($conn)
  echo "ok<br>";
else echo "not ok<br>";
  $sql = "select username from user";
$result = mysqli_query($conn,$sql);
if($result)
  echo "ok result<br>";
else 
  echo "no result<br>";
?>

输出结果为:

  

OK
  没有结果

以下是我在数据库中的内容

enter image description here

5 个答案:

答案 0 :(得分:2)

正如所指出的,user是一个保留字 - 但你应该能够用反引号封装user

<?php
    $servername="localhost";
    $username="b6_17093244";
    $password="password1";
    $dbName="b6_17093244_math";

    $conn = new mysqli($servername, $username, $password, $dbName);

    echo ( $conn ? 'ok' : 'not ok' ) . '<br />';

    $sql = "select `username` from `user`;";

    $result = mysqli_query($conn,$sql);

    echo ( $result ? 'ok result' : 'no result' ) . '<br />';
?>

以下对我来说很好 - 在我的情况下,该表名为users,而不是user

<?php

    $dbhost =   'localhost';
    $dbuser =   'root'; 
    $dbpwd  =   'xxx'; 
    $dbname =   'experiments';

    $conn   =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
    echo ( $conn ? 'db connection ok' : 'db connection failed' ).'<br />';

    $sql='select `username` from `users`';

    $res=$conn->query( $sql );

    echo ( $res ? 'ok result' : 'no result' ) . '<br />';

    while( $rs=$res->fetch_object() ) echo $rs->username.'<br />';

    $conn->close();

?>
/*
    output
    ------    
    db connection ok
    ok result
    tommy
    joey
    freddy    
*/

答案 1 :(得分:1)

试试这个并发布结果

<?php
$servername="localhost";
$username="b6_17093244";
$password="password1";
$dbName="b6_17093244_math";
$conn = new mysqli($servername, $username, $password, $dbName);
if($conn->connect_errno)
  echo "connect error". $conn->connect_error;
else 
   echo "not ok<br>";
$sql = "select `username` from `user`";
$result = mysqli_query($conn,$sql);
$conn->error();
echo "numof rows".$result->num_rows
if($result->num_rows>0)
  echo "ok result<br>";
else 
  echo "no result<br>";
?>

答案 2 :(得分:1)

似乎你没有获取所选对象

    if ($result = $mysqli->query($conn, $sql)) {
    echo "ok result<br>";
    while($obj = $result->fetch_object()){
       echo $obj->username . '<br/>';
    }
} 

答案 3 :(得分:1)

因为您正在混合MySQLi的两种不同用途

首先,您使用基于类的对象连接到数据库。并使用只调用函数进行查询。而是这样做:

# Here changed new mysqli
# to mysqli_connect
$conn = mysqli_connect($servername, $username, $password, $dbName);

答案 4 :(得分:0)

问题出在我的主机名中。它应该是这样的:a7h1.byethost6.com,而不是localhost。托管站点中显示的示例是“localhost”,我遵循了这些示例,但结果证明是错误的。

感谢所有帮助过的人!