Problem with returning rows using PHP - php

<?php
if (isset($_GET['flyerID']))
$FlyerID = $_GET['flyerID'];
$DBConnect = #mysqli_connect("host", "UN", "pword")
Or die("<p>Unable to connect to the datbase server.</p>" . "<p>Error Code ".mysqli_connect_errno().": ".mysqli_connect_error()) . "</p>";
$DBName = "agentsleuthdb";
#mysqli_select_db($DBConnect, $DBName)
Or die("<p>Unable to select the database.</p>" . "<p>Error Code " . mysqli_errno($DBConnect) . ": " . mysqli_error($DBConnect)) ."</p>";
$TableName = "FEEDBACK";
$SQLstring = "SELECT * FROM $TableName order by FIRSTNAME";
$QueryResult = #mysqli_query ($DBConnect, $SQLstring)
Or die("<p> Unable to exequte Select query.</p>"."<p>Error Code ".mysqli_errno($DBConnect) .": ".mysqli_error
($DBConnect))."</p>";
if (mysqli_num_rows($QueryResult) == 0){
exit("<p>There is no feedback</p>");
}
?>
<table border="1">
<tr>
<th width = "15%">First Name </th>
<th width = "15%">Last Name </th>
<th width = "15%">Email Addr </th>
<th width = "15%">Company </th>
<th width = "40%">Feedback </th>
</tr>
<?php
$Row = mysqli_fetch_row($QueryResult);
do {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td>{$Row[2]}</td>";
echo "<td>{$Row[3]}</td>";
echo "<td>{$Row[4]}</td></tr>";
$Row = mysqli_fetch_assoc($QueryResult);
} while ($Row);
mysqli_free_result($QueryResult);
mysqli_close($DBConnect);
?>
It only returns one row.. how can I return all entries?

Have you tried
while ($Row = mysqli_fetch_row($QueryResult))
Description here
or
while ($Row = mysqli_fetch_array($QueryResult, MYSQL_ASSOC))
Description here
Hope this helps.

In your code, only the first time you call mysqli_fetch_row, which makes an $Row an indexed array.
This is why you see output when you access the content of $Row with an index ($Row[0], $Row[1], etc..).
Afterwards, you mysqli_fetch_assoc which turns $Row in an associative array, thus accessing $Row with an index for your output doesn't work anymore.
Replace your do ... while loop by the first while loop aforloney suggested.

Related

PHP: No output from $row variable even if it is already defined

I don't know why it doesn't show up anything, I already tested my query and it is working in my phpmyadmin, but in my php code it does not work upon adding the AS keyword. My goal for this is to place a value to a variable coming from the SUM() keyword.
<?php
require_once "user-connect.php";
$user = $_SESSION['id'];
$sql = "SELECT SUM(total) AS sumz FROM cart WHERE userID = $user AND month(orderDate) = month(now()) AND day(orderDate) = day(now())";
$result = $link->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo $row['sumz'];
}
if (mysqli_query($link, $sql)) {
} else {
echo "Error: " . $sql . "" . mysqli_error($link);
} ?>
<table cellspacing="0">
<tbody>
<tr class="cart-subtotal">
<th>Cart Subtotal</th>
<td><span class="amount"><?php echo $row['sumz']; ?></span></td>
</tr>
You can use:
$sql = "SELECT SUM(total) FROM cart WHERE..."
And in HTML:
<td><span class="amount"><?php echo $row['SUM(total)']; ?></span></td>
Take a look at PHP fetch assoc guide.
while ($row = $result->fetch_assoc()) {
echo $row['sumz'];
}
An example of getting the SUM value
<?php
$sql="SELECT sum(amount) as total FROM table";
$result = mysqli_query($sql);
while ($row = mysqli_fetch_assoc($result)) {
echo $row['total'];
}
mysqli_close($con);
?>

Using 'foreach' values to plugin to database query then echo back into the table

After much tweaking I've finally got my table looking half decent:
<table id="Productslist" class="list">
<thead>
<tr>
<th> Part </th>
<th> Brand </th>
<th> Name </th>
<th> Quantity </th>
<th> Price </th>
</tr>
</thead>
<tbody>
<?php
$part = find_part();
foreach($parts_list as $col => $value) {
echo '<tr><td>'.$col.'</td><td>'.$value.'</td>
<td>'.$part['Name'].'</td></tr>';
}
?>
</tbody>
<tfoot>
<tr>
<td> Total </td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
The foreach loop works great! as it finds the column name and value within that column and inserts it into their own rows. Fantastic! Now I really want to use the $col and $value in a database query but when I try it either in the function or by global retrieval it doesn't work.... any insight?
function find_part() {
global $db;
global $col;
global $value;
$sql = "SELECT * FROM " .$col. "";
$sql .= "WHERE ID='" . $value ."' ";
$result = mysqli_query($db, $sql);
$part = mysqli_fetch_assoc($result);
mysqli_free_result($result);
return $part; }
or
function find_part($col, $value) {
global $db;
$sql = "SELECT * FROM " .$col. "";
$sql .= "WHERE ID='" . $value ."' ";
$result = mysqli_query($db, $sql);
$part = mysqli_fetch_assoc($result);
mysqli_free_result($result);
return $part; }
Both times the error_log says that its and undefined index.
You have to pass the values as a parameters in your function. Use following code.
<?php
foreach($parts_list as $col => $value) {
$part = find_part($col, $value);
echo '<tr><td>'.$col.'</td><td>'.$value.'</td>
<td>'.$part['Name'].'</td></tr>';
}
?>
Use this with below code.
function find_part($col, $value) {
global $db;
$sql = "SELECT * FROM " .$col. "";
$sql .= "WHERE ID='" . $value ."' ";
$result = mysqli_query($db, $sql);
$part = mysqli_fetch_assoc($result);
mysqli_free_result($result);
return $part;
}
You will be able to get $col and $value in this function.
Update
To skip an iteration in foreach loop
if($col == 'ID'){
continue; //it will skip the iteration and start next one.
}

While loop on php doesn't work why?

enter image description herei am working on project CMS with php and one of my while loops doesn't work and i cant find why.
i am echo on (td) inside of loop and nothing showed on the page but when i echo outside of while loop it work very well.
i have commentet the loop to see you.
Can you give me some help where i have the problem?
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
<th>Author</th>
<th>Comment</th>
<th>Email</th>
<th>Status</th>
<th>In Response to</th>
<th>Date</th>
<th>Approve</th>
<th>Unapprove</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM comments ";
$select_comments = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_comments)) {
$comment_id = $row['comment_id'];
$comment_post_id = $row['comment_post_id'];
$comment_author = $row['comment_author'];
$comment_content = $row['comment_content'];
$comment_email = $row['comment_email'];
$comment_status = $row['comment_status'];
$comment_date = $row['comment_date'];
echo "<tr>";
echo "<td>$comment_id</td>";
echo "<td>$comment_author</td>";
echo "<td>$comment_content</td>";
/
echo "<td>$comment_email</td>";
echo "<td>$comment_status</td>";
//THIS IS THE LOOP DOESN'T WORK
$query = "SELECT * FROM posts WHERE post_id = $comment_post_id";
$select_post_id_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($select_post_id_query)) {
$post_id = $row['post_id'];
$post_title = $row['post_title'];
echo "<td><a href='../post.php?p_id=$post_id'>$post_title</a></td>";
}
echo "<td>$comment_date</td>";
echo "<td><a href='comment.php?approve=$comment_id'>Approve</a></td>";
echo "<td><a href='comment.php?unapprove=$comment_id'>Unapprove</a></td>";
echo "<td><a href='comment.php?delete=$comment_id'>Delete</a></td>";
echo "</tr>";
}
?>
</tbody>
</table>
<?php
//approve posts
if(isset($_GET['approve'])){
$the_comment_id = $_GET['approve'];
$query = "UPDATE comments SET comment_status = 'approved' WHERE comment_id = $the_comment_id ";
$approve_comment_query = mysqli_query($connection, $query);
header("Location: comment.php");
}
//unapprove posts
if(isset($_GET['unapprove'])){
$the_comment_id = $_GET['unapprove'];
$query = "UPDATE comments SET comment_status = 'unapproved' WHERE comment_id = $the_comment_id ";
$unapprove_comment_query = mysqli_query($connection, $query);
header("Location: comment.php");
}
//delete posts
if(isset($_GET['delete'])){
$the_comment_id = $_GET['delete'];
$query = "DELETE FROM comments WHERE comment_id = {$the_comment_id} ";
$delete_query = mysqli_query($connection, $query);
header("Location: comment.php");
}
?>
You are overwriting variable $row in your second loop. You should change it eg. to $subRow to avoid such situation.
i have find the missing part on of my db with the connection.
THNX all you friends :D

How do I make the image in the MySQL table alter based on the id

I have a table with an "id" that automatically increment each time a new entry is added to the table. In the same table, I also store images.
Regardless of the id incrementing the image is always the same.
I would like the images to change based on the "id". How do I achieve this?
Find below my code to file: displayImage.php:
$link = mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db("flightSched") or die(mysql_error());
// get the image from the db
$sql = "SELECT image FROM flightSched";
// the result of the query
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
// set the header for the image
header("Content-type: image/jpeg");
echo mysql_result($result,1);
// close the db link
mysql_close($link);
And the code with the incrementing "id"
$result = mysql_query("SELECT id, flightNo, airline, origin, arrivalTime, status
FROM flightSched ")
or die(mysql_error());
$variable= 'id=basicBoard';
//echo $variable;
echo "<table border='1' id='customers'>";
echo "<tr> <th></th> <th>Flight No</th> <th>Airline</th> <th>Origin</th> <th>Arrival</th> <th>Status</th> ";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr " . $variable . "><td>";
echo '<img src="displayImage.php?id=' . $row['id'] . ' " width="40" height="40" >';
echo "</td><td>";
echo $row['flightNo'];
echo "</td><td>";
echo $row['airline'];
echo "</td><td>";
echo $row['origin'] . $row['id'];
echo "</td><td>";
echo $row['arrivalTime'];
echo "</td><td>";
echo $row['status'];
echo "</td></tr>";
if ($variable == 'id=basicBoard')
{
$variable = 'class=alt';
//echo $variable;
}
elseif ($variable == 'class=alt')
{
$variable = 'id=basicBoard';
//echo $variable;
}
}
echo "</table> <br/> <br/>";
Looking forward to your reply.
Any help is greatly appreciated!
You haven't used the ID to limit the results in your displayImage.php file.
Change
$sql = "SELECT image FROM flightSched";
to
$sql = "SELECT image FROM flightSched WHERE id = '$_GET[id]'";
This will get it working but is an example, but please sanitize the GET value instead of just using it directly in the sql.

Similar Queries different results, why?

This one is a bit perplexing since it works perfectly on some records, and not on others. I am trying to pull all records with a specific email and only getting one record in about half of the cases. I have two query sets one pulling the data one is pulling it half of the time.
The first that works all the time is:
$tiera = mysql_query("SELECT SUM(datamb) AS tiera FROM maindata2 WHERE dataplan = '2' and email='".mysql_real_escape_string($_POST['email'])."'");
$tiera1 = mysql_fetch_assoc($tiera);
$tiera2 = $tiera1['tiera'];
$tieradata = mysql_query("SELECT SUM(dataplan) as datatotal FROM maindata2 WHERE dataplan = '2' and email='".mysql_real_escape_string($_POST['email'])."'");
$tieradata1 = mysql_fetch_assoc($tieradata);
$tieradata2 = $tieradata1['datatotal'];
echo "<table id='display1'>
<tr>
<th>Tier:</th>
<th>Total Data in Tier:</th>
<th>Data Usage This Period:</th>
<th>Remaining:</th>
</tr>";
echo "<tr>";
echo "<td>A</td> ";
echo "<td>". $tieradata2 . " MB</td> ";
echo "<td>". $tiera2. " MB</td> ";
echo "<td>".($tieradata1['datatotal'] - ROUND ($tiera1['tiera'],2)) . "MB</td></font> ";
echo "</table>";
I cant use this for my second query because I need it in the loop like this:
$sql = "SELECT phonenumber,date,email, dataplan AS currentplan, SUM(datamb) AS value_sum FROM maindata2 WHERE email='".mysql_real_escape_string($_POST['email'])."' GROUP BY dataplan, phonenumber ";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No Data Found For This Email";
exit;
}
$row = mysql_fetch_assoc($result);
$query = mysql_query($sql) or die(mysql_error());
$header_printed = false;
while($row = mysql_fetch_array($query)) {
if ($row['phonenumber']) {
if ($header_printed === false) {
echo "
<table id='display'>
<tr>
<th>Phone Number:</th>
<th>Data Plan:</th>
<th>Data Usage This Period:</th>
<th>Remaining:</th>
<th>Date Reporting:</th>
</tr>";
$header_printed = true;
}
while ($row = mysql_fetch_assoc($result)){
echo "<tr>";
echo "<td>".$row['phonenumber'] . "</td> ";
echo "<td>".$row['currentplan'] . "MB</td> ";
echo "<td>".ROUND ($row["value_sum"],2) . "MB</td> ";
echo "<td><font color=$color>".($row['currentplan'] - ROUND ($row["value_sum"],2)) . "MB</td></font> ";
echo "<td>".$row['date'] . "</td></tr>";
}
}
echo "</table>";
So the question is, what is missing from the second query that is in the first?

Categories