PHP json_encode() in while loop - php

I am trying to use json_encode() in a while loop while getting database results. Here is my code:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>
The output of this is
{"response":"lastUserID lastUser lastXPos lastYPos"}
I want it to be...
{"response":["1 Alex 10 12", "2 Fred 27 59", "3 Tom 47 19"]}
etc.
So I want the json_encode() function to put ALL users into the array rather than the last one. How would I do this? Thanks

Try:
<?
$database = sqlite_open("thenew.db", 0999, $error);
if(!$database) die($error);
$query = "SELECT * FROM users";
$results = sqlite_query($database, $query);
if(!$results) die("Canot execute query");
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));
sqlite_close($database);
?>

Change this
while($row = sqlite_fetch_array($results)) {
$data = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
to
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}

Push each user to an array:
$data = array();
while($row = sqlite_fetch_array($results)) {
$data[] = $row['uid'] . " " . $row['username'] . " " . $row['xPos'] . " " . $row['yPos'];
}
echo json_encode(array("response"=>$data));

Related

Cant get table to update, delete and add with an extra code

So What Im trying to do is have the user add a code to a form, and fill the form out, A to add to the table, D to delete, U to update... The delete isnt working, neither is the insert, is it my logic? also I want to print the table only once, and sometimes it does it twice... any advice?
$Code=$_POST["Code"];
if ($Code == "A")
{
$sql = "INSERT INTO movieDATA values ('$idno', '$Name', '$Genre', '$Starring', '$Year', '$BoxOffice')";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "D")
{
$sql = "DELETE FROM movieDATA WHERE IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
elseif ($Code == "U")
{
$sql = "UPDATE movieDATA SET Name = '$Name', Genre = '$Genre', Starring = '$Starring', Year = '$Year', BoxOffice = '$BoxOffice' where IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
?>

Can't display database records

I want to echo sql database records in my page and I am using this code. When I run it doesn't display the result from the db. I have records in the database that match the criteria. I am new in php and sql so please tell where I have mistakes.
session_start();
if (!isset($_SESSION['name'])) {
header('Location:vhod.php');
exit;
}
$pageTitle = 'СЪОБЩЕНИЯ';
include 'includes/header.html';
$email = $_SESSION['email'];
$name = $_SESSION['name'];
include 'php/db_connect.php';
$msgs = '';
$query = 'SELECT `timestamp`, `to`, `sender`, `subject`, `msg` FROM msg WHERE `to`="$name"';
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$msgs = "ДАТА: " . $row["timestamp"] . " >> От: " . $row["sender"] . " >> Тема: " . $row["subj"] . " >> Съобщение: " . $row["msg"] . "<br>";
}
} else {
$msgs = "Нямате съобщения :(";
}
try modifying the lower part of your code like this.
$msgs = '';
$query = "SELECT * FROM msg WHERE to=$name";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$msgs = "ДАТА: " . $row['timestamp'] . " >> От: " . $row['sender'] . " >> Тема: " . $row['subj'] . " >> Съобщение: " . $row['msg'] . "<br>";
}
} else {
$msgs = "Нямате съобщения :(";
}

Why am I getting white spaces from this function?

I made a function that loops through all the posts in database and echo them. But there's a slight problem. I am getting whitespace between the name (title of the post) and the content, its like two lines or so. I want reason for this and solution. Thanks.
function read_all_posts(){
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'website';
$con = mysqli_connect($host, $username, $password, $database);
$query = "SELECT * FROM posts";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo "<h1>" . $row['name'] . "</h1>" . "<br>" . $row['content'] . "<br />" . "<i>" . $row['author'] . "</i>";
echo "<br>";
}
}
try,
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo "<h1>" . $row['name'] . "</h1>" . "<p>" . $row['content'] . "</p>" . "<p><i>" . $row['author'] . "</i></p>";
}

PHP / MySQL - Nested List by recommendations / IDs

We have on a social project a member database, which includes, which member recommended an other member. The fields of the database looks like this:
id | name | email | code | recruit_by
Now we want to print a nested list of the structure, who recommended whom on all deep levels.
We didn't get it running with the following code:
<?PHP
mysql_connect("www.mysqlserver.net", "database1", "password") or die(mysql_error());
mysql_select_db("project_db1") or die(mysql_error());
echo "<ul>";
$result = mysql_query("SELECT * FROM registration") or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<li class=\"level0\">" . $row['id'] . " - " . $row['name'] . " - " . $row['email'] . " - " . $row['recruit_by'] . "</li>";
// 1. Level
$result2 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row['id']) or die(mysql_error());
while($row2 = mysql_fetch_array($result2))
{
echo "<li class=\"level1\">1. " . $row2['id'] . " - " . $row2['name'] . " - " . $row2['email'] . " - " . $row2['recruit_by'] . "</li>";
// 2. Level
$result3 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row2['id']) or die(mysql_error());
while($row3 = mysql_fetch_array($result3))
{
echo "<li class=\"level2\">2. " . $row3['id'] . " - " . $row3['name'] . " - " . $row3['email'] . " - " . $row3['recruit_by'] . "</li>";
// 3. Level
$result4 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row3['id']) or die(mysql_error());
while($row4 = mysql_fetch_array($result4))
{
echo "<li class=\"level3\">3. " . $row4['id'] . " - " . $row4['name'] . " - " . $row4['email'] . " - " . $row4['recruit_by'] . "</li>";
// 4. Level
$result5 = mysql_query("SELECT * FROM registration WHERE recruit_by LIKE " . $row4['id']) or die(mysql_error());
while($row5 = mysql_fetch_array($result5))
{
echo "<li class=\"level4\">4. " . $row5['id'] . " - " . $row5['name'] . " - " . $row5['email'] . " - " . $row5['recruit_by'] . "</li>";
}
}
}
}
}
echo "</ul>";
?>
Very similar to an answer i gave here:
MySQL best practice: SELECT children recursive as performant as possible?
Again not the best use case for MySQL but yeah....
Dont do so many queries, do one
"SELECT * FROM registration"
Go through the result to build this as a tree like...
// use a database query to get this member info, here a simplified version
$member = array();
$member[] = array('id' =>'2', 'recruit_by' =>'1');
$member[] = array('id' =>'3', 'recruit_by' =>'2');
$member[] = array('id' =>'4', 'recruit_by' =>'3');
$member[] = array('id' =>'9', 'recruit_by' =>'1');
//use php to build a array containing all the recruit-relationships as a tree
function buildtree($member) {
$ref = array();
foreach($member as $mem){
$member_id = $mem['id'];
$parent = $mem['recruit_by'];
if(!is_array($ref[$member_id])) $ref[$member_id] = array('id' => $member_id);
if(!is_array($ref[$parent])) $ref[$parent] = array('id' => $parent);
$ref[$parent]['child'][] = &$ref[$member_id];
}
return $ref;
}
$tree = buildtree($member);
/// use a recursive function to output the tree
function echotree($tree, $parent = 0) {
foreach ($tree as $t) {
if($parent){
echo "$parent recruited " . $t['id'] . '<br>';
}
if(is_array($t['child']) && !$parent){
echotree($t['child'],$t['id']);
}
}
}
echotree($tree);
will give you:
2 recruited 3
1 recruited 2
1 recruited 9
3 recruited 4
should not be too hard to put this in whatever layout you wish.

drropdownlist values are not shown from the database on fom load

<?php
require_once("../../db_connect/db_connect.php");
$decoded = json_decode($_GET['json']);
$ias = $decoded->{'ias'};
$ian = $decoded->{'ian'};
$select = "select iacode,ianame from isdsmot_ia_creation";
$res = mysql_query($select);
while ($row = mysql_fetch_array($res)) {
$ias = $row['iacode'];
$ian = $row['ianame'];
$ia=$ias."|".$ian;
echo "<OPTION value = \"" . $row[0] . "|" . $row[1] . "\">" . $ia . "</OPTION>";
}
$result=$ia;
if ($result) {
echo "Successful" . mysql_error();
} else {
echo "Unsuccess" . mysql_error();
}
?>
Will this help you : add around your
<?php
require_once("../../db_connect/db_connect.php");
$decoded = json_decode($_GET['json']);
$ias = $decoded->{'ias'};
$ian = $decoded->{'ian'};
$select = "select iacode,ianame from isdsmot_ia_creation";
$res = mysql_query($select);
echo '<select name="myDropDown">';
while ($row = mysql_fetch_array($res)) {
$ias = $row['iacode'];
$ian = $row['ianame'];
$ia=$ias."|".$ian;
echo "<OPTION value = \"" . $row[0] . "|" . $row[1] . "\">" . $ia . "</OPTION>";
}
echo '</select>';
$result=$ia;
if ($result) {
echo "Successful" . mysql_error();
} else {
echo "Unsuccess" . mysql_error();
}
?>

Categories