PHP mysqli_fetch_assoc Assistance Please - php

This may have been asked and answered already but I could not find a solution that works for what I am trying to do. I need to determine the end of an associative array created by mysqli_fetch_assoc($result). The code I have is:
$query = "SELECT * " .
"FROM songs;";
$result = mysqli_query($connection, $query);
$number = mysqli_num_rows($result);
while($row = mysqli_fetch_assoc($result)){
if($number !== 0){
echo "{'title':'" .$row['song_name'] .
"'file':'" . $row['song_path'] . "'},<br /><br />";
} else {
echo "{'title':'" .$row['song_name'] .
"','file':'" . $row['song_path'] . "'}<br /><br />";
}
$number--;
}
Someone please tell me what I am doing wrong. What I want to do is echo the first part of the "if" statement and if the row is the last in the array I want to echo the else "without the comma at the end before the two break tags. It is returning all of the rows in the database but I just can't get rid of the comma if it is the end of the array. I am having a whale of a time with this. I know this might be easy stuff but I am new to PHP and it is throwing me for a loop. Please help!

Can you Try this,
$i=1;
while($row = mysqli_fetch_assoc($result)){
$comma =",";
if($i==$number){
$comma ="";
}
echo "{'title':'" .$row['song_name'] .
"'file':'" . $row['song_path'] . "'}".$comma."<br /><br />";
$i++;
}

You should try
...
if($number > 1){
...
Or you can do it as
...
$json = '';
while($row = mysqli_fetch_assoc($result)){
$json .= "{'title':'" .$row['song_name'] .
"'file':'" . $row['song_path'] . "'},";
}
if(strlen($json) > 0)
$json = substr($json,0, strlen($json)-1);
echo $json;

You use $number-- after one row is over so $number will be equal to 0 after all rows have been processed. So all you need to do is put $number-- before all the if clause
while($row = mysqli_fetch_assoc($result)){
$number--;//move to here
if($number !== 0){
echo "{'title':'" .$row['song_name'] .
"'file':'" . $row['song_path'] . "'},<br /><br />";
} else {
echo "{'title':'" .$row['song_name'] .
"','file':'" . $row['song_path'] . "'}<br /><br />";
}
//$number--; moved up
}
Now it should works!! :)

Related

no data gets print where the query returns too many results

I have a query which is supposed to retrieve data from mysql and print it on the browser. It is working with a few rows of data but when the data gets bigger it just stops working and doesn't give any errors.
$result = mysql_query($query);
$json_array = array();
while($row = mysql_fetch_assoc($result)){
$json_array[] = $row;
}
print mysql_error();
print json_encode($json_array);
I have tried everything but nothing seems to work.
I'm very surprised it works at all.
This would work if $row was formatted.
Use foreach()
I doubt this would work either:
foreach($json_array as $row){
echo "$row<br>\n"
}
This should work (replace colx with the name of the table columns):
foreach($json_array as $row){
echo $row['col1'] . ', ' . $row['col2'] . ', ' . $row['col2'] . "<br>\n"
}
foreach($json_array as $row){
echo $row['name'] . ', ' . $row['address'] . ', ' . $row['phone'] . "<br>\n"
}
#Lessmore has right, maybe the PHP process has reached the memory limits in the server, try with less columns or registers, but I understand your need, then you need to write your self json_encode code to write row by row. Some like this:
$first = null;
header('Content-Type: application/json');
echo '[';
while ($row = mysql_fetch_assoc($result)) {
if ($first) {
echo ',';
}
echo json_encode($row);
!$first && $first = true;
}
echo ']';
exit;

Put results in different divs depending on what comes out of the database?

How it looks:
https://jsfiddle.net/jef2L8m6/
How it should look:
https://jsfiddle.net/jef2L8m6/1/
I know it looks really bad, this is just for testing purposes only.
Some of the Backend Code:
<?php //Selects all of the logged in users messages.
$name = $_SESSION["name"];
$con = mysqli_connect('localhost','root','','chat');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM `chat` ORDER BY date";
$result = mysqli_query($con,$sql);
$numrows = mysqli_num_rows($result);
if( $numrows == "0" or !isset($_SESSION["name"])){
echo "<div class='msg'>You are not registered (Or there are no messages to display)</div>";
exit();
}else{
echo "";
}
echo "<div class='msg_container'>";
while($row = mysqli_fetch_array($result)) {
echo "<div class='msg_user'>";
echo "<div class='username_user'><span>" . $row['username'] . "</span></div>";
echo "<div class='message_user'><span>" . $row['message'] . "</span></div>";
echo "</div>";
}
echo "";
mysqli_close($con);
?>
Thank you so much for taking your time to read this.
I am trying to figure out how I would change the div tags of each separate user depending on their name?
Is there any way to do this using PHP, I have tried doing 2 separate query's of one that selects just the users messages and another that selects everyones (excluding the users)
But none of them worked due to it not ordering them correctly.
Could I somehow change the div's using PHP if the username that comes out is not equal to the username in the session?
Thank's so much, if you don't think I explained this very well please give me some feedback and I will change/add what you need, THANK YOU!
Thank you so much "u_mulder", you have been very helpful in making me think of a simple way to solve this problem.
I was thinking way too complex for something so simple!
Here is the final code for anyone who this may help:
while($row = mysqli_fetch_array($result)) {
$class_msg = "msg";
$class_username = "username";
$class_message = "message";
if ($row['username'] == $_SESSION['name']) {
$class_msg = "msg_user";
$class_username = "username_user";
$class_message = "message_user";
}
echo "<div class='$class_msg'>";
echo "<div class='$class_username'><span>" . $row['username'] . "</span></div>";
echo "<div class='$class_message'><span>" . $row['message'] . "</span></div>";
echo "</div>";
}
while($row = mysqli_fetch_array($result)) {
$class = 'msg';
if ($row['username'] == $_SESSION['name']) {
$class = 'msg_user';
}
echo "<div class='" . $class . "'>";
// other codes here
}

extract array values from a function

Below is a function in PHP I created which returns some product information in an array. On the web page where I am calling this function I want to be able to specify exact array elements for example just the product description ($result2['itm_desc']). Please can someone point me in the right direction as to do this. I would assume you call a function like fetch array but i'm not quite sure how to execute this.
public function getAllReelImages(){
$sql = "SELECT id FROM $this->table3 WHERE itm_cat = 2 ORDER BY id ASC";
echo "<br /><br />";
$stmt = mysqli_query($this->connection, $sql);
/*fetch values*/
while($result = mysqli_fetch_array($stmt)){
echo "<br /><br />";
$sql2 = "SELECT itm_details.id,itm_details.itm_make,itm_details.itm_model,itm_details.itm_desc,itm_pic_detail.itm_pic_name, itm_value.itm_sale_price
FROM
itm_details, itm_pic_detail, itm_value
WHERE
itm_details.id = {$result['id']} AND itm_pic_detail.id = {$result['id']}
AND itm_value.id = {$result['id']} ORDER BY id ASC";
$stmt2 = mysqli_query($this->connection, $sql2);
while($result2 = $stmt2->fetch_array()){
echo ($result2['id']); echo"<br />";
echo ($result2['itm_make']); echo"<br />";
echo ($result2['itm_model']); echo"<br />";
echo ($result2['itm_desc']); echo"<br />";
echo ($result2['itm_sale_price']); echo"<br />";
echo "<img src='$this->dir"."{$result2['itm_pic_name']}'><br />";
echo"<br />";
echo $value;
}
}
}
First of all.. Your code is pretty bad. I made it little bit more clear. For example: echo ($result2['id']); echo"<br />"; TO-> echo $result2['id'] . '<br />'; (for future references.)
They way your code is at the moment. You wont add anything to an array, since you echo them right away. I made my version, that would first create the array and then later you can use that array..in any way you want :)
And doesn't the ORDER BY use by default as ASC?
I also changed the first query more dynamic.
NOTE: I'm not very good with mysql table joining, somebody must validate the second query. But in my eyes, its absolutely incorrect. However, I'm posting this in the reference for creating an array with a function and then displaying it.
NOTE2: I hope your question was about PHP o.0
# This should be in some class ?!
function getAllReelImages ($category) {
$sql = "SELECT * FROM `" . $this->table3 . "` WHERE `itm_cat` = '" . $category . "' ORDER BY `id` ASC";
$stmt = mysqli_query($this->connection, $sql);
while($result = mysqli_fetch_array($stmt)) {
$sql2 = "SELECT `itm_details.id`, `itm_details.itm_make`, `itm_details.itm_model`, `itm_details.itm_desc`, `itm_pic_detail.itm_pic_name`, `itm_value.itm_sale_price` FROM `itm_details`, `itm_pic_detail`, `itm_value` WHERE `itm_details.id` = '" . $result['id'] . "' AND `itm_pic_detail.id` = '" . $result['id'] . "' AND `itm_value.id` = '" . $result['id'] . "' ORDER BY `id` ASC";
$stmt2 = mysqli_query($this->connection, $sql2);
while($result2 = $stmt2->fetch_array()){
$returns[$result2['id']]['id'] = $result2['id'];
$returns[$result2['id']]['itm_make'] = $result2['itm_make'];
$returns[$result2['id']]['itm_model'] = $result2['itm_model'];
$returns[$result2['id']]['itm_desc'] = $result2['itm_desc'];
$returns[$result2['id']]['itm_sale_price'] = $result2['itm_sale_price'];
$returns[$result2['id']]['itm_pic_name'] = $this->dir . $result2['itm_pic_name'];
}
}
return $returns;
}
# Display the results:
echo '<br /><br />';
foreach (getAllReelImages(2) as $img_id => $img_value) {
echo $img_id . '<br>';
echo $img_value['itm_make'] . '<br>';
echo $img_value['itm_model'] . '<br>';
echo $img_value['itm_desc'] . '<br>';
echo $img_value['itm_sale_price'] . '<br>';
echo $img_value['itm_pic_name'] . '<br>';
echo '<hr>';
}
echo '<br />';

Grouping WHILE loop results

At the moment I'm using a WHERE loop to display 2 columns of information in my database. Here's the code:
$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
/*These if & while statements decide whether or not the information should be displayed. If no results are returned from the query above then an alternative message is shown.*/
if (mysql_num_rows($result2) > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"] . "<br/><br/>";
}
}
else {
echo "Error";
}
This outputs the following:
08:00:00-12:30:00
13:30:00-16:30:00
09:00:00-17:00:00
18:00:00-20:00:00
09:00:00-17:00:00
18:00:00-20:00:00
08:00:00-17:00:00
18:00:00-20:00:00
09:00:00-17:00:00
18:00:00-20:00:00
Now, what I need to do is group every 2 lines that are turned so instead it would look like:
08:00:00-12:30:00 13:30:00-16:30:00
09:00:00-17:00:00 18:00:00-20:00:00
09:00:00-17:00:00 18:00:00-20:00:00
08:00:00-17:00:00 18:00:00-20:00:00
09:00:00-17:00:00 18:00:00-20:00:00
Is this possible? Thanks for any help
edit: Thanks for all the answers everyone...I used Shakti's answer as it was the first one I saw but by the looks of it everyone's are pretty similar.
if(mysql_num_rows($result2) > 0)
{
$count=0;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC))
{
echo $row["open"] . "-" . $row["close"] ;
if ($count % 2 !=0 )
{
echo "<br/><br/>";
}
$count++;
}
}
try this:
$lines = 1;
if(mysql_num_rows($result2) > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"];
echo (($lines%2 == 0)?"<br/><br/>":'');
$lines++;
}
} else {
echo "Error";
}
if(mysql_num_rows($result2) > 0){
$counter = 0;
while($row = mysql_fetch_array($result2, MYSQL_ASSOC)){
echo $row["open"] . "-" . $row["close"] . " ";
if(++$counter % 2 == 0){
echo "<br/><br/>";
$counter = 0;
}
}
}
if($result2) {
$printTimes = function($r) {echo $row["open"] . "-" . $row["close"];};
$newLine = false;
while ($row = mysql_fetch_assoc($result2))
{
$printTimes($row);
echo $newLine ? '<br /><br />' : ' ';
$newLine = !$newLine;
}
}
My version of code.
$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
if(mysql_num_rows($result2) > 0) {
while (true) {
$row1 = mysql_fetch_array($result2, MYSQL_ASSOC);
$row2 = mysql_fetch_array($result2, MYSQL_ASSOC);
if (!($row1 and $row2)) break;
echo $row1["open"] . "-" . $row1["close"] . " ";
echo $row2["open"] . "-" . $row2["close"] . "<br/><br/>";
}
} else {
echo "Error";
}
$i=1;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
if ($i == 1) {
echo $row["open"] . "-" . $row["close"];
$i++;
} else {
echo $row["open"] . "-" . $row["close"] . "<br /><br />";
$i=1;
}
Output <br/><br/> only on every other iteration of the loop. (BTW, a <p> or <ul> or <div> would be more semantic.)
$counter = 0;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"] . " ";
// Break line after every two items
$counter = ($counter + 1) % 2;
if ($counter == 0)
echo "<br/><br/>";
}
$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
/*These if & while statements decide whether or not the information should be displayed. If no results are returned from the query above then an alternative message is shown.*/
int row_count=mysql_num_rows($result2)
if(row_count > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
row_count--;
echo $row["open"] . "-" . $row["close"] ;
if(row_count > 0 && ($row = mysql_fetch_array($result2, MYSQL_ASSOC)){
row_count--;
echo $row["open"] . "-" . $row["close"] ;
}
"<br/><br/>"
}
} else {
echo "Error";
}
should do it, u may need to catch if there is an odd number

help with php search

How would I do let the user know if there wasnt any rows found?
And if it finds (for example) 26 rows I want it to print that it found 26 hits (Your search for "hey" gave 26 results)
$name = mysql_real_escape_string($_POST['player_name']);
$q = mysql_query("SELECT * FROM players WHERE name LIKE '%$name%'");
while ($row = mysql_fetch_array($q)) {
$name = $row['name'];
echo "<ul>\n";
echo "<li>" . "" .$name . " </li>\n";
echo "</ul>";
}
Use mysql_num_rows:
$rowCount = mysql_num_rows($q);
if ($rowCount === 0)
{
echo 'Found nothing!';
}
else
{
echo "Found $rowCount rows!";
while ($row = mysql_fetch_array($q))
{
$name = $row['name'];
echo "<ul>\n";
echo "<li>" . "" .$name . " </li>\n";
echo "</ul>";
}
}
Check out mysql_num_rows
mysql_num_rows
$numberOfResults = mysql_num_rows($q);

Categories