我已从 php 连接到 mySql 数据库。我想从中获取两列的详细信息。当我尝试访问它们时,它输出 null。 当我在 phpmyAdmin 数据库工具中运行时,相同的查询字符串工作正常。
下面是我的代码:
$servername = "mysql";
$username = "$$$$$$$$$";
$password = "%%%%%%%%%%";
$databasename = 'blog';
// Create connection
$conn = new mysqli($servername, $username, $password, $databasename);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
$select_sql = "Select site_url from sites where id LIKE '%website1Modal%'";
$result = $conn->query($select_sql);
if ($result->num_rows > 0) {
echo "in if loop";
echo $result[0];
}
上面的代码输出:“连接成功”和“在 if 循环中”。
有人可以告诉我我犯了什么愚蠢的错误吗?
最佳答案
if
不会让您陷入循环。 if
是一个控制结构。使用 while
进入循环并将 fetch
放入其中,以便可以访问结果。
尝试一下:
$servername = "mysql";
$username = "$$$$$$$$$";
$password = "%%%%%%%%%%";
$databasename = 'blog';
// Create connection
$conn = new mysqli($servername, $username, $password, $databasename);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
$select_sql = "Select site_url from sites where id LIKE '%website1Modal%'";
$result = $conn->query($select_sql);
if ($result->num_rows > 0) {
echo "in if control";
while($row = $result->fetch_array()) { //this is optional; if only one row the while can be removed. e.g. $row = $result->fetch_array();
echo 'in while loop';
echo $row['site_url'];
} //if removing while remove this as well
}
您可以在此处阅读有关 if
和 while
控件的更多信息。
http://php.net/manual/en/control-structures.if.php
http://php.net/manual/en/control-structures.while.php
这是 query 的手动输入确实如此。
重要的一点
For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object.
并且因为您有一个 mysqli_result 对象
,您需要将其发送到 fetch这将
Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset.
关于php - 无法从 PHP 访问数据库值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33683946/