Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php switching to mysqli: num_rows issue

Tags:

php

mysqli

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.

like image 217
Hezerac Avatar asked Feb 17 '23 12:02

Hezerac


1 Answers

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() ;    

?>
like image 117
Mr. Radical Avatar answered Feb 27 '23 17:02

Mr. Radical