在我的PHP代码中,我很容易将记录写入我的数据库,但由于某种原因,我无法读取任何信息.我的PHP代码是:
$conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM companies"; if ($conn->query($sql) === TRUE) { echo "query success"; while($row = $result->fetch_assoc()) { echo "ID: " . $row["ID"]. " - Name: " . $row["name"]. "
"; } } else { echo "query failure"; echo "Error: " . $sql . "
" . $conn->error; } $sql = "INSERT INTO companies (name) VALUES ('mycompany')"; if ($conn->query($sql) === TRUE) { echo "insert success"; } else { echo "insert failure"; echo "Error: " . $sql . "
" . $conn->error; }
我运行它时从浏览器获得的输出是:
query failureError: SELECT * FROM companies
insert success
我已尝试过撇号,插入符号,$ sql字符串中的引号.我试过在HeidiSQL中运行这个查询,它运行正常.我出错的任何想法?有什么更基本的建议我可以尝试缩小问题的根源吗?
谢谢!
使用mysqli->query()
with SELECT
语句返回的实例mysqli_result
.它与true(=== true
)不同,但也不代表错误.
而且,$result
未定义.
请改用:
$conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM companies"; if (($result = $conn->query($sql)) !== FALSE) { echo "query success"; while($row = $result->fetch_assoc()) { echo "ID: " . $row["ID"]. " - Name: " . $row["name"]. "
"; } } else { echo "query failure"; echo "Error: " . $sql . "
" . $conn->error; } ...
这只是将您的=== TRUE
支票更改为!== FALSE
.MySQLi::query()
在失败时返回布尔值FALSE,对于没有结果集的成功查询或者结果集成功后返回布尔值TRUE mysqli_result
.这也将query()的结果分配给$result
.