php switching to mysqli: num_rows issue - php

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.

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

As it was said, you're not checking for the errors.
Run all your queries this way
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]");
if no errors displayed and var dumps are saying no data - then the answer is simple: your query returned no data. Check query and data in the table.

In PHP v 5.2 mysqli::num_rows is not set before fetching data rows from the query result:
$mysqli = new mysqli($host,$user, $password, $database);
if ($mysqli->connect_errno) {
trigger_error(sprintf(
'Cannot connect to database. Error %s (%s)',
$mysqli->connect_error,
$mysqli->connect_errno
));
}
$sql = "SELECT * FROM data_table";
$result = $mysqli->query($sql);
// a SELECT query will generate a mysqli_result
if ($result instanceof mysqli_result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$num_rows = $result->num_rows; // or just count($rows);
$result->close();
// do something with $rows and $num_rows
} else {
//$result will be a boolean
}
$mysqli->close() ;

Related

mysql result into php array

I'm trying to convert the result that i'm getting from mysql to a php array
can anyone helps me
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "women";
$conn = new mysqli($servername, $username, $password, $dbname);
$id=$_GET['id'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS,
DAY(ADDDATE(ADDDATE(`dateDebutC`, `dureeC`),`dureeR`))AS DAYS
FROM normalW
where id = '$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
foreach($new_array as $array){
echo $row['DAYS'].'<br />';
echo $row['MONTHS'].'<br />';
}
} else {
echo "0 results";
}
$conn->close();
?>
Problem solved Thank you guys
To answer your question you must first declare the new array
$new_array = array();
Then loop through your query results to populated the array
while ($row = $result->fetch()) {
$new_array[] = $row;
}
But as one of the comments mentioned you really should be using prepared statements to protect yourself from sql injection.
$stmt = $mysqli->prepare("SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS, DAY(ADDDATE(ADDDATE(`dateDebutC`, `dureeC`),`dureeR`)) AS DAYS FROM normalW where id = ?");
/* bind parameters i means integer type */
$stmt->bind_param("i", $id);
$stmt->execute();
$new_array = array();
while($row = $stmt->fetch()) {
$new_array[] = $row;
}

android - php fetch mysql data by user id

This my PHP URL for fetching the data from MySQL. I need to make mysqli_fetch_array code saying if filled uid in the app-data table is the same with uid in users table fetch the data from all row in app-data to the uid like every user show his items from app-data table.
$host = "";
$user = "";
$pwd = "";
$db = "";
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "SELECT * FROM app_data ORDER By id";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
I think this is the correct answer:
<?php
$host = "";
$user = "";
$pwd = "";
$db = "";
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$sql = "SELECT * FROM app_data WHERE u_id=".$_POST['posted_uid']." ORDER By id";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
Little tip for the future:
Don't search exactly what you want, only search in parts.

mysql to pdo JSON for ios

I'm trying to convert this mysql code into PDO code, yet I can only return one of my rows in JSON whereas the mysql code allows me all the rows.
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM questions ORDER BY RAND() LIMIT 40";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
And here is the PDO code I've got to so far
$db = new PDO('mysql:host=***;dbname=***', $user, $pass);
$query = "SELECT * FROM questions ORDER BY RAND() LIMIT 40";
$stmt = $db->prepare($query);
$stmt->execute();
$records = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$records = $row;
}
echo json_encode($records);
It looks like I have to fill some more of this post out with random gobldygook as it seems I haven't already gotten to the point.
forgot to push each row into records, therefore
$records[] = $row;
or use fetchAll()
$db = new PDO('mysql:host=***;dbname=***', $user, $pass);
$query = "SELECT * FROM questions ORDER BY RAND() LIMIT 40";
$stmt = $db->prepare($query);
$stmt->execute();
$records = $stmt->fetchAll(PDO::FETCH_ASSOC); // to get all records at once
echo json_encode($records);

Handling error report

I am new in PHP so I have to apologize for such a dumb question, but I am not sure how to find the right answer. I should check if my final result is empty (if $sql found anything). If it didnt find I would like to get some notification example "The list is empty". That message will also be visible from Android app when I call the url?
<?php
$host = "";
$user = "";
$pwd = "";
$db = "";
$con = mysqli_connect($host, $user, $pwd, $db);
if(mysqli_connect_errno($con)) {
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
// query the application data
$sql = "SELECT * FROM lista WHERE Grad='".$_GET['grad']."' AND Predmet='".$_GET['predmet']."'";
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
mysqli_close($con);
echo json_encode($rows);
If mysqli_num_rows returns 0, you have no records.
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) == 0) {
$rows = "no rows found";
} else {
$rows = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$rows[] = $row;
}
}
mysqli_close($con);
echo json_encode($rows);

mysql_query SELECT do not give the desired result

The following code always displays
rows = 0
eventhough the table contains Ravi in the field 'to'. Does anyone know what is wrong with this code?
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE to = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$result = mysql_fetch_array($result);
echo $result["to"] + " " + $result["from"];
} else {
echo 'rows = 0';
}
} else {
echo 'empty for Ravi';
}
//} else {
//}
?>
to is a reserved word in MySQL, if you want to use it you must encase it in backticks:
.... WHERE `to` = ...
I have not look at your code but I recommend looking at
http://php.net/manual/en/intro.mysql.php
this before you continue to use mysql and not mysqli. It isn't that different but mysqli seems to have a wrapper over mysql and uses the "->" to instantiate new classes for a connection. If that makes any sense.
Try this:
<?php
$response = array();
$con = mysql_connect("localhost","root","");
if(!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db("algopm1",$con);
//if (isset($_POST['to'])) {
$to = "Ravi";
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'");
if (!empty($result)) {
if (mysql_num_rows($result)>0) {
$row = mysql_fetch_array($result);
echo $row["to"] + " " + $row["from"];
} else {
echo 'rows = 0';
}
} else {
echo "empty for $to";
}
//} else {
//}
?>
MYSQLI version + some adjustments:
<?PHP
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE {
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
$result = mysqli_query($link, $query);
if (mysql_num_rows($result)>0) {
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo $row["to"]. "+". $row["from"];
}
}
ELSE {
echo 'rows = 0';
}
}
mysqli_close($link);
?>
I would like to credit #njk and #Wezy for their contribution with regard to the reserved word to in mysql. The WHILE loop is not necessary if the table events can only contain one "to" in this case "Ravi". I suspect that the number of events can be greater than one.
#Wezy has a point but let's do the troubleshooting:
As #JonathanRomer in his comment suggested, do:
$result = mysql_query("SELECT *FROM `events` WHERE `to` = '$to'") or die(mysql_error());
What does it say? Does it fail at all?
Or, just before mysql_query do:
die("SELECT *FROM `events` WHERE `to` = '$to'");
this will print faulty query being executed. Next, fire up mysql console or PHPMyAdmin and try executing this query manually.
Again, what does it say?
Actually, my main purpose was to encode this message and receive it on a mobile device by using JSON. This is the full code. For normal checking purpose, instead of using json_encode(*), the values can be displayed individually. This is the solution I got and it is working perfectly for receiving the data in an android app on which I am working.
<?php
$host = "localhost";
$user = "root";
$password = "";
$database="algopm1";
$response = array();
$mysqli = new mysqli($host, $user, $password, $database);
if (mysqli_connect_errno()){
$response["success"] = 0;
$response["message"] = mysqli_connect_error();
echo json_encode($response);
}
if(isset($_POST['to'])) {
$to = $_POST['to'];
$query = "SELECT *FROM `events` WHERE `to` = '$to'";
if($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->store_result();
$i = 0;
if($stmt->num_rows > 0) {
$stmt->bind_result($rowto, $rowfrom, $rowevent);
$response["events"] = array();
while($stmt->fetch()) {
$events = array();
$events["to"] = $rowto;
$events["from"] = $rowfrom;
$events["event"] = $rowevent;
array_push($response["events"], $events);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No events found";
echo json_encode($response);
}
$stmt->close();
}
} else {
$response["success"] = 0;
$response["message"] = "Required fields are missing";
echo json_encode($response);
}
$mysqli->close();
?>

Categories