printing out a json array - php

I am trying to figure out how to print a json array. I am trying to handle this from Android code but it is not working. I believe the problem lies in how I am outputting json. the below doesn't show anything. The script is below:
<?php
// Create connection
$conn=mysqli_connect("localhost","dhdkahd","dsdajdsa","dsadjsajd");
$json = array();
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!$conn->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $conn->error);
}
$sql='SELECT title, description, country, city, rate FROM discounts';
$rs=$conn->query($sql);
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
/*$rs->data_seek(0);
while($row = $rs->fetch_assoc()){
echo $row['title'] . '<br>';
}*/
while ( $row = $rs->fetch_assoc() )
{
$json[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}
}
//echo json_decode($json);
echo json_encode($json);
mysqli_close($conn);
?>
thanks in advance

You can only call json_encode once. You're double-encoding everything.
The line where you're adding data to the array needs to be
$json[] = $row;
Then, when the array is built up, you encode the entire thing in one single call:
echo json_encode($json);

You call json_encode twice. To fix it, change your code to:
if($rs === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
/*$rs->data_seek(0);
while($row = $rs->fetch_assoc()){
echo $row['title'] . '<br>';
}*/
while ( $row = $rs->fetch_assoc() )
{
$json[] = $row;
}
}
//echo json_decode($json);
echo json_encode($json);
mysqli_close($conn);
?>

Related

Showing one row. Need to show it in a loop

I am trying to figure out how to use this in a loop. Any help will be appreciated.
$conn = mysql_connect("localhost", "some_user", "password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("some_db")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT favid FROM ajaxfavourites";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
}
mysql_free_result($result);
Currently it displays results as:
116677889922
I need them to show them as (the way they are displayed in DB):
1166
7788
9922
PS I am aware that this function is deprecated, I am just trying to fix one of my older sites.
choose One of these ways:
echo $row["favid"]."<br>";
echo $row["favid"]."\n";
echo $row["favid"].PHP_EOL;
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
echo "\r\n";
}
You can simply echo the value with '<br/>' or '<p>' like following:
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"] . '<br/>';
}
OR
while ($row = mysql_fetch_assoc($result)) {
echo '<p>' . $row["favid"] . '</p>';
}
Also you can just put all favid into array and then in another loop, can customize how to show them, like following:
while ($row = mysql_fetch_assoc($result)) {
$ids[] = $row["favid"];
}
foreach($ids AS $idv) {
echo '<p>' . $idv . '</p>';
}

my pdo connection doesn't work

Echoing to my previous question about SQL-injection. I'm trying to set up a PDO connection.
For that I want to replace my old code with the new:
Here is the old
$conn = mysql_connect("localhost", "sec", "dubbelgeheim") or
die('Error: ' . mysql_error());
mysql_select_db("bookshop");
$SQL = "select * from productcomment where ProductId='" . $input . "'";
$result = mysql_query($SQL) or die('Error: ' . mysql_error());
$row = mysql_fetch_array($result);
if ($row['ProductId']) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
} else
echo "No Record!";
mysql_free_result($result);
mysql_close();
And here is the new:
$input = $_GET['input'];
if ($input) {
$user= 'sec';
$pass = 'dubbelgeheim';
try {
$dbConn = new PDO('mysql:host=127.0.0.1;dbname=bookshop', $user, $pass);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$escaper = $db->real_escape_string($input);
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $escaper);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
while ($row = $result->fetch_assoc()) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
}
}
else {
echo 'No record!';
}
$result->free();
$db->close();
}
When I tried this new code.. It gives the following error:
Error!: SQLSTATE[HY000] [1045] Access denied for user
'sec'#'localhost' (using password: YES)
I also tried to replace localhost with 127.0.0.1.
My goal is to make my page secure for SQL-injection.
May anyone have a great solution!
The code looks ok at first glance.
Try this solution. It looks like this anonymus user might be the problem.
EDIT: (as suggedted in comments)
In summary:
The recommended solution is to drop this anonymous user. By executing
DROP USER ''#'localhost';

Displaying ALL data from sql table in PHP?

When I print my code it only prints the question and description of id = 1 but not the rest of the table.
here is my code.
Please show me how to print my entire table which has like 20 questions or so...and also please show me how to make it so that the questions stay on the browser (even when I refresh the page) because currently the data does not stay on the browser when i refresh the page.
Thanks So Much!
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
} else {
echo "failed to fetch array";
}
}
?>
You need a for each loop:
<?php
require_once "connection.php";
if(isset($_POST['submit'])) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME );
if($conn->connect_error) {
die("connection error: " . $conn->connect_error);
} else {
echo "Submit button connected to database!";
}
$question = $_POST['question'];
$description = $_POST['description'];
$sql = " INSERT INTO `ask` (question_id, question, description) VALUES
(NULL, '{$question}', '{$description}' ) ";
if($conn->query($sql)) {
echo "it worked";
} else {
echo "error: " . $conn->error;
exit();
}
$query = "SELECT * FROM `ask` ";
if( $result = $conn->query($query)) {
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
} else {
echo "failed to fetch array";
}
}
?>
All I've done there is change:
$fetch = $result->fetch_assoc();
echo "<p>{$fetch['question']}</p>";
echo "<p>{$fetch['description']}</p>";
to:
$fetch = mysql_fetch_array($result, MYSQL_ASSOC);
foreach($fetch as $ques) {
echo "<p>" . $ques['question'] . "</p>";
echo "<p>" . $ques['description'] . "</p>";
}
fetch_assoc() — Fetch a result row as an associative array
so it gets only 1 row you need to loop through the rest of the rows check the examples reference from php docs

PostgreSql All returning results are "Array"

I have this piece of code
<?
$db = pg_connect("host=h port=p dbname=dbn user=usr password=pass");
if ($db) {
echo 'Connection attempt succeeded.' . '<br>' . '<br>';
}
else{
echo 'Connection attempt failed.' . '<br>' . '<br>';
}
$query = "SELECT column1 FROM table";
$result = pg_query($db, $query);
while ($row = pg_fetch_array($result)) echo $row. '<br>'. '<br>';
echo pg_dbname($db). '<br>' ;
echo pg_get_pid($db);
?>
The result should be three numeric values. When I run it, all I get are three strings "Array".
Connection attempt succeeded.
Array
Array
Array
dbname
pid
Can anyone help, please?
DO:
while ($row = pg_fetch_all($result)) echo $row['column1']. '<br>'. '<br>';
OR debug:
while ($row = pg_fetch_all($result)) var_dump($row) . '<br>'. '<br>';

Printing result of mySQL query with INNER JOIN

I have a working SQL statement that returned correct results when I checked it on MAMP.
SELECT `questions`.`questionID` AS question, `questions`.`questionText`,
`questions`.`categoryID`,`answers`.`answerID`,`answers`.`answerText`,
`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`
But I can't figure out how to print the output with php. Please help. This is the code:
<html>
<body>
<?php
header('Content-Type: text/html; charset=utf-8');
$con=mysqli_connect("localhost","root","root","Theory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questions'.'questionID'] . "}"; //this is not the full print
echo "{" . $row['questions'.'questionText'] . "}"; //just for chaking
echo "}";
}
mysqli_close($con);
?>
</body>
</head>
I get:"{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}" echoed.
You're executing a query again inside your if condition... But the $sql query is empty because the variable is not defined!
replace if (!mysqli_query($con,$sql)) with if (!$result) since you have already executed the query in the rows above.
EDIT to answer the question's comments:
when you're fetching the resulting array, you don't need to specify the table alias but just the column name OR the column alias if present.
Try this:
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questionID'] . "}"; //this is not the full print
echo "{" . $row['questionText'] . "}"; //just for checking
echo "}";
}
$sql is aparently not set. You can do:
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}

Categories