I created a table in Wampserver64 with 7 columns (companyname, cod, bign, stop, date, time, price) and 5 rows. In the PHP section I want to get the information of all rows as JSON output, but in the output only the last row information is read. I provided the PHP code and output below.
<?php
$con=mysqli_connect('localhost','root','','u656325986_login');
$response=array();
$result=mysqli_query($con,"select * from travel");
if(mysqli_num_rows($result)>0){
enter code here
while($row=mysqli_fetch_array($result)){
$temp=array();
$temp["companyname"]=$row["companyname"];
$temp["cod"]=$row["cod"];
$temp["bign"]=$row["bign"];
$temp["stop"]=$row["stop"];
$temp["data"]=$row["data"];
$temp["time"]=$row["time"];
$temp["price"]=$row["price"];
$response["travel"]=array();
array_push($response["travel"],$temp);
}
$response["t"]=1;
echo json_encode($response);
}
else{
$response["message"]="not fonud";
echo json_encode($response);
}
?>
Output
{"travel":[{"companyname":"alborz ","cod":"333333333","bign":"yazd","stop":"gheshm","data":"22/22/33","time":"23:60","price":"123456789"}],âtâ:1}
As you can see, the output is just the end of the line. The rest of the rows are not read.
You are creating a new empty array on each iteration.
Define this outside of the while loop so each array_push will add items to it:
$response["travel"]=array();
i think you should put $response["travel"]=array(); outside while loop
, replace your code to be
<?php
$con=mysqli_connect('localhost','root','','u656325986_login');
$response=array();
$result=mysqli_query($con,"select * from travel");
if(mysqli_num_rows($result)>0){
$response["travel"]=array();
while($row=mysqli_fetch_array($result)){
$temp=array();
$temp["companyname"]=$row["companyname"];
$temp["cod"]=$row["cod"];
$temp["bign"]=$row["bign"];
$temp["stop"]=$row["stop"];
$temp["data"]=$row["data"];
$temp["time"]=$row["time"];
$temp["price"]=$row["price"];
array_push($response["travel"],$temp);
}
$response["t"]=1;
echo json_encode($response);
}
else{
$response["message"]="not fonud";
echo json_encode($response);
}
?>
Well you don't need most of the code anyway.
<?php
$con=mysqli_connect('localhost','root','','u656325986_login');
$response=array('travel' => array());
$result=mysqli_query($con,"select * from travel");
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
$response["travel"][] = $row;
}
$response["t"]=1;
echo json_encode($response);
}
else{
$response["message"]="not fonud";
echo json_encode($response);
}
?>
Related
I am making a blog and I want to fetch all rows using a pdo statement but no matter what I do only one row comes back even though there are two rows in my database.
Here's the code sample where I connect:
<?php
try{
$link=new PDO('mysql:host=127.0.0.1;dbname=blog1','root','');
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
echo $e->getMessage();
die();
}
?>
Then I try to fetch all rows
<?php
require 'Escape.php';
$posts_query=$link->query('SELECT * FROM posts');
$posts_query->execute();
/* variable that holds a with the database link and query in it then fetches
all the data related to the query into and assoc array */
$result=$posts_query->fetchAll();
//counting all rows
$count=$posts_query->rowCount();
if($count>0){
foreach($result as $r){
$id= $r['id'];
$title= $r['title'] ;
$content=$r['content'];
$date= $r['date'];
//admin buttons
$admin="";
//keeping title safe
$Title=htmlentities($title);
//keeping output safe
$output=htmlentities($content);
// styling the posts to be echoed with secure variables
$posts= "<div><h2><a href='view_post.php?pid=$id' class='names'>$Title</a>
</h2><h3>$date</h3><p>$output</p>$admin</div>";
escape($posts);
}
echo"<div id=posts>$posts</div>";
} else{
echo 'There are no posts to display.';
}
?>
Your $posts's value is reset to the latest row when you loop, either you append the value of each post using concat . operator:
if($count>0){
$posts = "";
foreach($result as $r){
// Define your variable
$posts .= "<div><h2><a href='view_post.php?pid=$id' class='names'>$title</a></h2><h3>$date</h3><p>$output</p>$admin</div>";
escape($posts);
}
echo"<div id=posts>$posts</div>";
} else { ... }
Or printing each post while looping:
if($count>0){
$posts = "";
echo "<div id='posts'>";
foreach($result as $r){
// Define your variable
$posts = "<div><h2><a href='view_post.php?pid=$id' class='names'>$title</a></h2><h3>$date</h3><p>$output</p>$admin</div>";
escape($posts);
echo $posts;
}
echo"</div>";
} else { ... }
Looks like you are re-assigning posts on every iteration, try adding the values to an array and imploding them when you would like to echo them out.
require 'Escape.php';
$posts_query=$link->query('SELECT * FROM posts');
$posts_query->execute();
$result=$posts_query->fetchAll();
$count=$posts_query->rowCount();
if($count>0){
$posts=[];
foreach($result as $r){
$id= $r['id'];
$title= $r['title'] ;
$content=$r['content'];
$date= $r['date'];
$admin="";
$Title=htmlentities($title);
$output=htmlentities($content);
// Add the HTML to the $posts array, also taking advantage of NOWDOCS
$posts[]= <<< HTML
<div>
<h2>
<a href='view_post.php?pid={$id}' class='names'>{$Title}</a>
</h2>
<h3>{$date}</h3>
<p>{$output}</p>
{$admin}
</div>
HTML;
escape($posts);
}
echo"<div id='posts'>" . implode('', $posts) . "</div>";
} else {
echo 'There are no posts to display.';
}
Here is a reference to PHP HEREDOCS.
After following some answers and articles finally i came up with the function that will generate key(number) automatically when it is not exist in the database and codes works, but the problem is when the code exist the notification that "CODE EXIST" form something like a loop and print multiple notifications. Base on my codes where do i get it wrong and how can I fix it?
<?php
//HERE IS THE FUNCTION
function MyFunction($xIsConnection){
// CODE GENERATION
//$Code=(rand(10,1000));
$Code='001';
$query= "SELECT * FROM parent WHERE code='$Code'";
if($result= mysqli_query($xIsConnection,$query)){
if(mysqli_num_rows($result)>0){
echo " CODE EXIST<br>";
// CALL FUNCTION TO GENERATE NEW CODE
MyFunction($xIsConnection);
}
else{
echo "NOT EXIST <br>";
echo $Code;
}
}
else{
echo"failed";
}
}
require_once('dbConnect.php');
MyFunction($con);
mysqli_close($con);
?>
The answer is never ending recursion.
<?php
//HERE IS THE FUNCTION
function MyFunction($xIsConnection){
// CODE GENERATION
//$Code=(rand(10,1000));
$Code='001';
$query= "SELECT * FROM parent WHERE code='$Code'";
if($result= mysqli_query($xIsConnection,$query)){
if(mysqli_num_rows($result)>0){
echo " CODE EXIST<br>";
// CALL FUNCTION TO GENERATE NEW CODE
MyFunction($xIsConnection); // this line is responsible for your error. Recursion
}
else{
echo "NOT EXIST <br>";
echo $Code;
}
}
else{
echo"failed";
}
}
require_once('dbConnect.php');
MyFunction($con);
mysqli_close($con);
?>
It's not a duplicate question about UTF-8 Unicode.
I am new to php and I am trying to create a json response.
I added data into my database properly as follows.
Then I tried to connect to DB and i did it successfully .
but after that when I tried to create a json response by using the following code, it doesn't shows any json response .
My PHP code is :
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','qwerty');
define('DB','carol');
$con = mysqli_connect(HOST,USER,PASS,DB);
if (!$con)
{
echo "Please try later..";
}
else
{
echo "DB Connected..";
}
$sql = "SELECT * from songs";
$res = mysqli_query($con,$sql);
if (!$res)
{
echo "query failed..";
}
else
{
echo "Query success..";
echo (mysqli_num_rows($res));
}
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('title'=>$row[0]),
array('url'=>$row[1]),
array('lyrics'=>$row[2])
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
I'm getting only echo of DB Connected , Query Success and 14 (no of rows)
I'm trying PHP for the first time by using some online tutuorials.
if I did any mistake in my code,please help me to find my mistake.
Thank you in advance.
After I added echo var_dump($res);
I got
This code should return an array containing data from a WAMP server containing some entries about followers. Unfortunately it doesn't. Any help please?
<?php
include('ConnectionManager.php');
function getfollowers()
{
print "check";
//String query
$query="SELECT * FROM `followers` order by 'followerid'";
//execute query
$result=mysql_query($query);
//3mel array isma followers
$followers=array();
//jeeb number of rows
if(mysql_num_rows($result))
{
while($followers=mysql_fetch_assoc($result))
{
$followers[]=$followers;
}
return $followers;
}
}
?>
You're re-declaring $followers inside your loop. Change it to something else
while($row = mysql_fetch_assoc($result)) {
$followers[]=$row;
}
your issue is:
$followers[]=$followers;
you are overriding it.
while($row=mysql_fetch_assoc($result))
{
$followers[]=$row;
}
should fix the issue
Why is this not working?
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
$result = mysqli_fetch_assoc($query);
$title = mysqli_real_escape_string($connect,trim($result['title']));
$message = mysqli_real_escape_string($connect,trim($result['message']));
while(($result = mysqli_fetch_assoc($query))){
echo $title;
echo '<br/>';
echo '<br/>';
echo $message;
}
?>
where as this works -
<?php
echo $title;
?>
SORRY TO SAY, BUT NONE OF THE ANSWERS WORK. ANY OTHER IDEAS?
If your mysqli query is returning zero rows then you will never see anything printed in your while loop. If $title and $message are not set (because you would want reference them by $result['title'] & $result['message'] if that are the field names in the database) then you will only see two <br /> tags in your pages source code.
If the while loop conditional is not true then the contents of the while loop will never execute.
So if there is nothing to fetch from the query, then you won't see any output.
Does you code display anything, or skip the output entirely?
If it skips entirely, then your query has returned 0 rows.
If it outputs the <br /> s, then you need to check your variables. I could be wrong, not knowing te entire code, but generally in this case you would have something like
echo $result['title'] instead of echo $title
If $title and $message come from your mysql query then you have to access them through the $result array returned by mysqli_fetch_assoc.
echo $result['title'];
echo $result['message'];
Also if your using mysqli you'd be doing something like this:
$mysqli = new mysqli("localhost", "user", "password", "db");
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
print $row['title'];
}
$result->close();
}
Try this:
<?php
$result = mysql_query($query);
while($row = mysqli_fetch_assoc($result)){
echo $title.'<br/><br/>'.$message;
}
?>
Does this work;
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
while(($result = mysqli_fetch_assoc($query))){
echo $result['title'];
echo '<br/>';
echo '<br/>';
echo $result['message'];
}
?>
Basically I've made sure that it's not picking the first result from the query & then relying on there being more results to loop through in order to print the same message repeatedly.