looping througn mysql result in php - php

I have this piece of code
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["user_id"] = $row["user_id"];
$product["user_name"] = $row["user_name"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
and it gave me this result
{"products":[{"user_id":"2","user_name":"BOZ2"},{"user_id":"25","user_name":"POZ"},{"user_id":"28","user_name":"a"}],"success":1}
and now i am using ...
$row = $stmt->fetch();
if ($row) {
$sql = "select statement";
$stmt = $db->prepare( $sql );
// execute the query
$stmt->execute();
// fetch the results into an array
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
$response["products"] = array();
$product["user_name"] = $row["user_name"];
$product["user_id"] = $row["user_id"];
// convert to json
$json = array_push($response["products"], $product);
// echo the json string
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
and it is giving me this..looping same result
{"products":[{"user_name":"BOZ2","user_id":"2"}],"success":1}{"products":[{"user_name":"BOZ2","user_id":"2"}],"success":0,"message":"success"}
how can i make it loop through all the results

fetchAll returns all rows in an array. All you need is just this
$sql = "select statement";
$stmt = $db->prepare( $sql );
$stmt->execute();
$response = array();
$response["products"] = $stmt->fetchAll( PDO::FETCH_ASSOC );
$response["success"] = 1;
echo json_encode($response);

Related

MySQL fetch command isn't returning data

Want the PHP script to pull all data from the database and display it on screen. But can't find the most efficient method to display the records without using the $query_params variable as it generates an error with the parameters in but cannot run without an array?
//initial query
$query = "Select * FROM tbl_data";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
And here is the display code
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["username"] = $row["username"];
$post["title"] = $row["title"];
$post["message"] = $row["message"];
I would be really grateful if you could help, thank you!

importing mysql query result to json

i am trying to get data from remote mysql database and importing it to json
the connection is ok, the problem is that the result that finally echoed from json is not normal, this is my php code
<?php
require("config.inc.php");
$query = "Select * FROM comments";
$res = mysql_query($query);
$rows = mysql_fetch_assoc($res);
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["username"] = $row["username"];
$post["title"] = $row["title"];
$post["message"] = $row["message"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
and this is the result echoed to the page:
{"success":1,"message":"Post Available!","posts":[{"username":"1","title":"1","message":"1"},{"username":"r","title":"r","message":"r"},{"username":"t","title":"t","message":"t"},{"username":"t","title":"t","message":"t"}]}
while my database table "comments" contain these data:
post_id username title message
1 reda test title 2 test message xxx
2 reda2 title 2 message 2
please help
thanks.
You are only returning 1 row / array by using
$rows = mysql_fetch_assoc($res);
So when you do
foreach ($rows as $row) {
you are trying to get a multidimensional array loop, from a single array. That is why each posts value is the 1st character from each column from the 1 returned row/array.
You need to build your $rows array. Try changing
$rows = mysql_fetch_assoc($res);
to
$rows = array();
while($result = mysql_fetch_assoc($res)){
$rows[] = $result;
}
You're not reading your result set from MySQL correctly. You're fetching just the first row and treating that as the entire results set. You need to loop, retrieving each row in turn.
Try this:
$query = "Select * FROM comments";
$res = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($res)!= 0) {
$response = array();
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
while ($row = mysql_fetch_assoc($res)) {
$post = array();
$post["username"] = $row["username"];
$post["title"] = $row["title"];
$post["message"] = $row["message"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
}
// echoing JSON response
echo json_encode($response);
Note: I haven't tested this code.
2nd Note - you shouldn't be using mysql_*() for new code - it's deprecated. Swicth to mysqli_*() or PDO.

PHP doesnt display anything

Hi guys I'm new to PHP and I'm trying to display all info in my admin table. When I test my PHP file it gives me a blank page, here is my php code. There's no error but I get a blank page and nothing was returned when I execute it.
<?php
require('connect.inc.php');
require('admin.config.inc.php');
require('core.inc.php');
if (!empty($_POST)) {
//initial query
$query = "SELECT * FROM admin where username = :user";
$query_params = array(':user' => $_POST['username']);
//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["users"] = array();
foreach($rows as $row) {
$user = array();
$user["username"] = $row["username"];
$user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];
//update our repsonse JSON data
array_push($response["users"], $user);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}
} else {}
?>
Put this at the head of the script to see what response you get. Then others may be able to help you according to the error you get.
ini_set('display_errors',1);
error_reporting(E_ALL);
I see you have also began with:
if (!empty($_POST)) {
}
$_POST IS An associative array of variables passed to the current script via the HTTP POST method.
$_POST is defined where. this should be some thing like $_POST['user']
You begin with:
if (!empty($_POST)) {
which is empty by default, so you go directly to the else statement which is empty as well!
You are declaring $user = array(); inside the loop, It has to be outside of the loop
$user = array();
foreach($rows as $row) {
$user["username"] = $row["username"];
$user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];

SQL query in php file error

I have this code passing a variable from a url. When i use $_GET method it returns me a json with no products found but when i give manually the the value that $user_email has from the url it returns me the correct json! what is wrong and how can i correct it? thank you
URL: http://***********/android_connect/get_all_products.php?user_email=m
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
$user_email= $_GET['user_email'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$test= "SELECT *FROM products WHERE user_email= '" .$user_email. "'";
//echo $test;
$result = mysql_query($test) or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["firstname"] = $row["firstname"];
$product["lastname"] = $row["lastname"];
$product["email"] = $row["email"];
$product["phone"] = $row["phone"];
$product["address"] = $row["address"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
$product["user_email"] = $row["user_email"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
Try this:
$test= "SELECT * FROM products WHERE user_email = '$user_email'";
EDIT:
$test= "SELECT * FROM products WHERE user_email = $user_email";

select statement always return the last inserted row in php mysql

When I wrote the select statement it always return the last inserted row in the database. What is the problem, and how can I fix it?
Important NOTE: A friend of mine took the same code and it worked for her properly!
if (isset($_GET["name"])) {
$pid = $_GET['name'];
// get a product from products table
//)or die(mysql_error()
$result = mysql_query("SELECT * FROM food WHERE name = $pid");
//mysql_query($result,$con);
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["name"] = $result["name"];
$product["unit"] = $result["unit"];
$product["calory"] = $result["calory"];
$product["carbohydrate"] = $result["carbohydrate"];
$product["category"] = $result["category"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No item found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
} */
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["name"] = $result["name"];
$product["unit"] = $result["unit"];
$product["calory"] = $result["calory"];
$product["carbohydrate"] = $result["carbohydrate"];
$product["category"] = $result["category"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
}
replace this with
while(mysql_num_rows($result) > 0 && ($result = mysql_fetch_array($result))) {
$product = array();
$product["name"] = $result["name"];
$product["unit"] = $result["unit"];
$product["calory"] = $result["calory"];
$product["carbohydrate"] = $result["carbohydrate"];
$product["category"] = $result["category"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
}
the result is array and you are not looping through it
so it givesonly one element in the array
This is because mysql_fetch_array is not in a loop, place it into the while loop and check.
Simply putting everything in a loop will not fix this. The code your gave will give the same result.. the last one.
$product needs to be declared BEFORE the loop otherwise, it will always be reset. Also, in order to populate the $product array without overwriting you will need to make it multidimensional
$product[]['name'] = $result["name"];
The ideal way of storing the products would be like this.. in my opinion.
$product = array();
while($result = mysql_fetch_array($result)) {
$product[$result['id']] = $result;

Categories