MySQL fetch command isn't returning data - php

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!

Related

JSON fields returning null when containing html tags

I am trying to expose some data in a table that contains HTML tags, when I access the page all of the fields not containing HTML are fine but any containing html return null.
I have tried setting the fields to VarChar and Text but neither seem to work. The table is also set to utf8_general_ci.
request_step_content.php
<?php
header("Content-Type:application/json");
header("Access-Control-Allow-Origin: *");
$user = "userName";
$pass = "userPassword";
$table = "myTable";
$db=new PDO("mysql:host=localhost;dbname=$table", $user, $pass);
$query = "SELECT * FROM steps";
try {
$stmt = $db->query($query);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error.";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if($rows) {
$response["success"] = 1;
$response["message"] = "Step";
$response["step"] = array();
foreach ($rows as $row) {
$post = array();
$post["id"] = $row["intID"];
$post["heading"] = $row["strStepheading"];
$post["keyPrinciple"] = $row["strKeyPrinciple"];
$post["pillar"] = $row["strPillar"];
$post["introduction"] = $row["memIntroduction"];
$post["actionSteps"] = $row["memActionSteps"];
$post["actionPoints"] = $row["memActionPoints"];
$post["studyAndUnderstanding"] = $row["memStudyUnderstanding"];
array_push($response["step"], $post);
}
echo json_encode($response);
}
else {
$response["success"] = 0;
$response["message"] = "No Steps Available";
die(json_encode($response));
}
?>
json response
{"success":1,
"message":
"Step",
"step":[{"id":"1",
"heading":"Test Heading",
"keyPrinciple":"Key Principle: Test Key Principle",
"pillar":"Pillar 1: Pillar",
"introduction":null,
"actionSteps":null,
"actionPoints":null,
"studyAndUnderstanding":null}]}
The problem will be in encoding. Columns in DB tables can be UTF-8 but stored data doesnt have to be in UTF-8. PHP function json_encode accepts only UTF-8 data. Check your stored DB data.
I fixed the issue with some help of #Fky's answer regarding encoding.
Using utf_encode() I now have all fields including the html content in my JSON fields. Here's the edited code:
foreach ($rows as $row) {
$post = array();
$post["id"] = $row["intID"];
$post["heading"] = $row["strStepheading"];
$post["keyPrinciple"] = $row["strKeyPrinciple"];
$post["pillar"] = $row["strPillar"];
$post["introduction"] = utf8_encode($row["memIntroduction"]);
$post["actionSteps"] = utf8_encode($row["memActionSteps"]);
$post["actionPoints"] = utf8_encode($row["memActionPoints"]);
$post["studyAndUnderstanding"] = utf8_encode($row["memStudyUnderstanding"]);
Thank you for the help all.

looping througn mysql result in 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);

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"];

Query a base64 image from sql and decode it

I am trying to pull pictures from a table row that are base64 encoded. I need to decode them and display on a webpage. I would really like to put them into a slideshow but that is another topic!
Here is the query so far
<?php
require("config.inc.php");
//initial query
// table name is pictures and table row is picture
$query = "Select * FROM pictures";
//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"] = "Photos Available!";
$response["posts"] = array();
// only 3 rows in table - post_id, username, picture
foreach ($rows as $row) {
$post = array();
$post["post_id"] = $row["post_id"];
$post["username"] = $row["username"];
$post["picture"] = $row["picture"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Photos Available!";
die(json_encode($response));
}
?>
The problem is decoding it. Here is what it shows so far
http://www.photosfromfriends.com/webservice/gallery.php
This is only for one picture (post) The table might have 50 pictures in it and each will need to be displayed (hence the desire for a slideshow). This is way over my head and I would really appreciate any help.
try this code, please justify according to your code:
$data = json_decode($json, true);
//print_r($data);
$picture = base64_decode($data['posts'][0]['picture']);
header("Content-type: image/png");
echo $picture;
You must decode only decoded data for the image, and don't forget to use header

Categories