php only returning 1 row from database - php

I have the following php code (in a file returndata.php) to retrieve messages for a user:
$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response['message'] = $row["message"];
$response['date'] = $row["date"];
$response['sender'] = $row["sender"];
$response['receiver'] = $row["receiver"];
}
echo json_encode($response);
} else {
echo " 0 results";
}
Then the javascript is as follows (displays the message and some information on it such as the sender, date etc. on the webpage):
$.post(
"returndata.php",
{ messagesforaccount: userAccount },
function(response) {
var sender = response.sender;
var receiver = response.receiver;
var message = response.message;
var date = response.date;
console.log('Retreived data: ', sender, receiver, message, date);
p = document.createElement('p')
p.innerHTML = message + '<br>' + 'sent by ' + sender + ' at ' + date
listmessages.appendChild(p)
}, 'json'
);
This only adds one message to the page (the last one in the database). What should the php be so it loops through all results, and for each result it adds the message to the webpage?

You did a little bit mistake there. If you want associative array for multiple data then you should have a two dimensional array and you must have an index for second dimensional array as well
<?php
$sql = 'SELECT * FROM usertimes WHERE receiver ="'. $messagesforaccount. '"';
$result = $conn->query($sql);
$response = array();
$index = 0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[$index]['message'] = $row["message"];
$response[$index]['date'] = $row["date"];
$response[$index]['sender'] = $row["sender"];
$response[$index]['receiver'] = $row["receiver"];
$index++;//incrementing index variable
}
echo json_encode($response);
} else {
echo " 0 results";
}
?>
In return you can iterate that array in this way
for ($i=0;$i<count($response);$i++)
{
echo $response[$i]['message'] . "<br>" ;
echo $response[$i]['date'] . "<br>" ;
echo $response[$i]['sender'] . "<br>" ;
echo $response[$i]['receiver'] . "<br>" ;
}

You need to respond with all of them in an array like this:
$sql = 'SELECT `message`, `date`, `sender`, `receiver` FROM `usertimes` WHERE `receiver` ="'. $messagesforaccount. '"';
You should only request the fields you need. This improves performances and reduces overhead. Later, you can just push the whole row to the response.
$result = $conn->query($sql);
$response = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response[] = $row;
}
echo json_encode($response);
} else {
echo " 0 results";
}

Related

php get all values from database and return to xml field?

i need some help with my app . I have this code :
realtime.php
$jogador = Jogador::getSaldoJogadorByEmail($email);
$premio = Premio::getValorPremioByTipo($tipo);
$participante = Participantes::getATotalParticipantesFromPA1();
$doc = new DOMDocument("1.0");
$action = $doc->createElement('action');
$action = $doc->appendChild($action);
$jogador = $doc->createElement('jogador1', $jogador);
$jogador = $action->appendChild($jogador);
$premio = $doc->createElement('premio1', $premio);
$premio = $action->appendChild($premio);
$participante = $doc->createElement('participante1', $participante);
$participante = $action->appendChild($participante);
$output = $doc->saveXML();
header("Content-type: application/xml");
echo $output;
and i have this function that is only p+assing one value instead of passing all the content of the database :
static function getTotalParticipantesFromPA1(){
$db = new mysqli("localhost","******","****","participantes");
$query = "SELECT * FROM premioacumulado1";
$result = $db->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
if(mysqli_num_rows($result) > 0 ){
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$id = $row['id'];
$username = $row['username'];
$m = "ID: " . $id . " " . "User: " . $username . "\n";
return $m;
}
}else{
$db->close();
return NULL;
}
}
all other fields are working in realtime , but this one is only getting one value from the database ...
how to get all the values from the database?
Edited - 22-05-2022
static function getTotalParticipantesFromPA1(){
$db = new mysqli("localhost","*****","*****","participantes");
$query = "SELECT * FROM premioacumulado1";
$result = $db->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
if(mysqli_num_rows($result) > 0 ){
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$id = $row['id'];
$username = $row['username'];
$m = "ID: " . $id . " " . "User: " . $username . "\n";
}
return $m; // if i put it here it only returns the last value in the data base .
}else{
$db->close();
return NULL;
}
}
static function getTotalParticipantesFromPA1(){
$db = new mysqli("localhost","*****","*****","participantes");
$query = "SELECT * FROM premioacumulado1";
$result = $db->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
if(mysqli_num_rows($result) > 0 ){
while($row = $result->fetch_array(MYSQLI_ASSOC)){
$id = $row['id'];
$username = $row['username'];
$m = "ID: " . $id . " " . "User: " . $username . "\n";
echo $m;// if i do a echo i get an error in the xml $participante variable(realtime.php) , maybe convert it here so it can take the result , but how ?
}
}else{
$db->close();
return NULL;
}
}
here is the script Js :
function getRealTime(){
//retrieve the DOM objects to place content
var domjogador1 = document.getElementById("saldo");
var dompremiovaloracu1 = document.getElementById("valorActualPremioAcu1");
var domparticipantes1 = document.getElementById("areaParticipantesAcu1");
//send the get request to retrieve the data
var request = new XMLHttpRequest();
request.open("GET", "realtimegame.php", true);
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
//parse the xml document to get each data element
var xmldoc = request.responseXML;
var xmljogador1 = xmldoc.getElementsByTagName("jogador1")[0];
var jogador1 = xmljogador1.childNodes[0].nodeValue;
var xmlpremio1 = xmldoc.getElementsByTagName("premio1")[0];
var premio1 = xmlpremio1.childNodes[0].nodeValue;
var xmlparticipante1 = xmldoc.getElementsByTagName("participante1")[0];
var participante1 = xmlparticipante1.childNodes[0].nodeValue;
domjogador1.innerHTML = jogador1;
dompremiovaloracu1.innerHTML = premio1;
domparticipantes1.innerHTML = participante1;
}
};
request.send();
}
here is the function that works , now with a more pretty result:
static function getBTotalParticipantesFromPA1(){
$db = new mysqli("localhost","root","","participantes");
$query = "SELECT * FROM premioacumulado1";
$result = $db->query($query);
$row = $result->fetch_array(MYSQLI_ASSOC);
$s = "<br />";
$data1 = array();
if(mysqli_num_rows($result) > 0 ){
do{
$data1[] = $row['username'] . " " . $row['id'] . "
";
}while($row = $result->fetch_array(MYSQLI_ASSOC));
return json_encode($data1);
}else{
$db->close();
return NULL;
}
}
I still wanted to print out something a little more pretty for end user to see . with this i get the line break in each value , but i still wanted to remove the "," from the output ... if anyone has something that can be used better then this please post it , thanks .

Want to echo variable, however no results are echoed

i receive "echo "Klaida!!!!"" meaning there is no results.
Could you please point out my mistake in code.
$dezesdezesId = $_GET["dezesId"];
$query = "SELECT * FROM dezes WHERE dezesId = '$dezesdezesId'";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows ($result) > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
$dezesPavadinimas = $row["pavadinimas"];
$dezesLikutis = $row["likutis"];
}
echo $dezesLikutis;
}
else
{
echo "Klaida!!!!" . mysqli_error($connection);
}
echo this inside your while loop.
while ($row = mysqli_fetch_assoc($result))
{
$dezesPavadinimas = $row["pavadinimas"];
$dezesLikutis = $row["likutis"];
echo $dezesLikutis;
}
and try to use '{$dezesdezesId}' your variable inside your query string

Search database using array and then echo/print result in foreach loop using PHP

I need to get variable code from URL so I $codes = $_GET['code']; (url example website.com/update?code[]=7291&code[]=9274&code[]=8264&) then I SELECT firstname FROM guests WHERE invitecode = $codes" then I output data and set as $relatives = $row["firstname"] and then later on in the file I need to echo/print print $relative.
Why is this not working for me?
... connection made ...
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE invitecode = $codes";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$relatives[] = $row["firstname"];
}
}
foreach ($relatives as $relative) {
print $relative;
}
Update:
So now using:
<?php
$codes = $_GET['code'];
$thecodes = "";
foreach($codes as $vals)
$thecodes .= (int)$vals . ",";
if($thecodes != "")
{
$thecodes = trim($thecodes, ",");
$sql = "SELECT firstname FROM guests WHERE invitecode IN ($thecodes)";
$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$relatives[] = $row["firstname"];
}
}
foreach ($relatives as $relative) {
print $relative;
}
}
else
{
}
?>
It works but I would like to enter the foreach ($relatives as $relative) { echo $relative; }; into a value like this $message = $firstname . " " . $lastname . " will be coming to your event. " . ;.
In the end it would turn out something like this: $message = $firstname . " " . $lastname . " will be coming to your event. " . foreach ($relatives as $relative) { echo $relative . " "; };.
For some reason it won't work when I combine them.
Use the IN operator for this.
<?php
$codes = $_GET['code'];
$thecodes = "";
foreach($codes as $vals)
$thecodes .= (int)$vals . ","; //Loop through making sure each is an int for security reasons (No sqli)
if($thecodes != "") //There is at least one code
{
$thecodes = trim($thecodes, ","); //Remove any additional commas
$sql = "SELECT firstname, lastname FROM guests WHERE invitecode IN ($thecodes)"; //Use the IN operator
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo $row["firstname"] . " " . $row["lastname"] . "is coming to your event";
}
}
}
else //No codes to be queried
{
}
?>
Can this be a solution for you?
$relatives = array(); // declare array
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE ";
foreach ($codes as $code) $sql .= "invitecode = " . intval($code) . " OR ";
$sql .= "1=2"; // simple way to remove last OR or to make sql valid if there are no codes
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
array_push($relatives, $row["firstname"]);
}
}
foreach ($relatives as $relative) {
print $relative;
}
I think this will work...
... connection made ...
$codes = $_GET['code'];
$sql = "SELECT firstname FROM guests WHERE invitecode = '$codes'";
$result = mysqli_query($conn, $sql) or die('-1' . mysqli_error());
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo ($row['firstname']);
}
}

build an array of an array from SQL query with php

I have the following working array of an array in PHP:
$explore1 = array
(
array("a.html", "A"),
array("b.html", "B"),
array("c","C")
);
$arrlength = count($explore1);
for($x = 0; $x < $arrlength; $x++) {
echo '<li>'.$explore1[$x][1].'</li>';
} }
I want to populate the explore1 array from SQL. If i simply change the code like below it has errors but I don't know what I'm suppose to do instead?
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$explore1 = array //IT DOESN'T LIKE THIS LINE
(
while($row = $result->fetch_assoc()) {
// BUILD SAME LINES AS ABOVE WITH ECHO
echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
}
);
Can anybody help?
Either you don't need $explore1 at all:
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
echo '<li>'.$row["name"].'</li>';
}
}
or if you need you can fetch_all():
$sql = 'SELECT url, name FROM explore_items WHERE menuID="item1"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$explore1=$result->fetch_all(MYSQLI_ASSOC);
foreach($explore1 as $row ) {
//echo "array('" . $row["url"]. ", '" . $row["name"]. "'),";
echo '<li>'.$row["name"].'</li>';
}
}
Please learn some php basics.
Defining an array of arrays is something like:
$explore1 = array();
while($row = $result->fetch_assoc()) {
$explore1[] = array($row["url"], $row["name"]);
}
You must populate the array inside the loop:
while($row = $result->fetch_assoc()) {
$explore1[$row["url"]] = $row["name"];
}

PHP - Not echoing data from a MySQL database, but no errors?

So I have this PHP code:
Note: I do use mysqli_connect() further up.
$result = mysqli_query($con,"SELECT * FROM `smf_messages` WHERE `id_board` = 18");
if(!$result) {
echo "<center><p>Couldn't fetch news posts. Error code 2.</p></center>";
mysqli_close($con);
} else {
$posts = array();
$topicbdy = array();
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$posts[$row['id_topic']] = $row['id_topic'];
$topicbdy[$row['id_msg']] = $row['id_msg'];
}
$display = max($posts);
$display2 = min($topicbdy);
$qry = "SELECT * FROM `smf_messages` WHERE `id_board` = 18 AND `id_topic` = " . $display . " AND `id_msg` = " . $display2;
$result2 = mysqli_query($con,$qry);
//echo $qry;
if(!$result2) {
echo "<center><p>Couldn't fetch news posts. Error code 3.</p></center>";
} else {
while($show = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
echo "<center><h1>" . $show['subject'] . "</h1></center><br /><br />";
echo "<center>" . $show['body'] . "</center><br />";
}
}
mysqli_free_result($result);
mysqli_free_result($result2);
mysqli_close($con);
It's supposed to get the latest topic out of the database for my SMF-based forum from the news board, by getting the highest topic id, but the lowest post id. It seems to be doing the query just fine, as I don't get any errors, but it doesn't show the subject or body. What should I do?
Your $result variable is wrong for second query fetch. For your second query
while($show = mysqli_fetch_array($result,MYSQLI_ASSOC))
Should be
while($show = mysqli_fetch_array($result2,MYSQLI_ASSOC))
^

Categories