php switching to mysqli: num_rows issue
mysqli, php
Solution
Try this:
<?php
// procedural style
$host = "host";
$user = "user";
$password = "password";
$database = "db";
$link = mysqli_connect($host, $user, $password, $database);
IF(!$link){
echo ('unable to connect to database');
}
ELSE {
$sql = "SELECT * FROM data_table LIMIT 1";
$result = mysqli_query($link,$sql);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $row['data'];
}
}
mysqli_close($link);
// OOP style
$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table LIMIT 1";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
if($result->num_rows == 1) {
$row = $result->fetch_array();
echo $row['data'];
}
$mysqli->close() ;
// In the OOP style if you want more than one row. Or if you query contains more rows.
$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
while($row = $result->fetch_array()) {
echo $row['data']."<br>";
}
$mysqli->close() ;
?>
Problem
I recently started updating some code to MySQL improved extension, and have been successful up until this point: ``` // old code - works $result = mysql_query($sql); if(mysql_num_rows($result) == 1){ $row = mysql_fetch_array($result); echo $row['data']; } // new code - doesn't work $result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); if($result->num_rows == 1) { $row = $result->fetch_array(); echo $row['data']; } ``` As shown I am trying to use the object oriented style. I get no mysqli error, and vardump says no data... but there definitely is data in the db table.