問題描述
mysql fetch 中的 $row 是什麼類型的變量? (What kind of variable is $row from a mysql fetch?)
I am growing extremely frustrated with this issue. I'm attempting to do a simple query but it won't work. It's extremely simple. I send an input via post and I've tested it already. The post variable is arriving in tact. The only issue is when I echo "$row['id']" i get a blank variable passed back to my html function every time. I created an alert for when i get the data back in my html file and it flashes a blank alert every time. Before arriving at this code I made the file echo "not found" if $row was empty and it was empty when I expected it to be. When it's not empty though, I can't use the variables stored in the associative array. Yes, "id" is absolutely there. I've checked the database and there is only one "classes" row for testing.
<?php
$tempClass = $_POST["class"];
$tempClassArray = explode("=",$tempClass);
$class = $tempClassArray[1];
$con=mysqli_connect("localhost","root","*****","*******");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM classes WHERE className LIKE '%$class%' OR
classNumber LIKE '%$class%' OR section LIKE '%$class%'");
while ($row = mysql_fetch_array($result))
{
echo $row['id'];
}
?>
參考解法
方法 1:
Try to print the $row variable first
print_r($row);
if it only print "array( )", then the query might have failed, you may try to echo it as well to see if there is any errors.
to answer the title, mysql_fetch_array Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.
reference: http://php.net/manual/en/function.mysql‑fetch‑array.php
ps: i think this should go to comment section, but since i dont have enough reputation,sorry :(
方法 2:
try this though it works same as previous but can give a try
while ($row = mysql_fetch_assoc($result))
{
echo $row['id'];
}
方法 3:
You are using a mysqli
query ‑
$result = mysqli_query($con, ....);
But trying to use a mysql
(not mysqli
) fetch
while ($row = mysql_fetch_array($result))
Try changing it to mysqli_fetch_array
while ($row = mysqli_fetch_array($result))
{
echo $row['id'];
}
it is common to accidentally mix up mysql
and mysqli
functions
(by Craig Lafferty、Hendyanto、Minav Patel、Sean)