IF statement within WHILE not working - php

I am working on a basic messaging system. This is to get all the messages and to make the row of the table that has an unread message Green. In the table, there is a column called 'msgread'. this is set to '0' by default. Therefore it should make any row with the msgread = 0 -> green. this is only working for the first row of the table with the code i have - i verified that it is always getting a 0 value, however it only works the first time through in the while statement ..
require('./connect.php');
$getmessages = "SELECT * FROM messages WHERE toperson = '" . $userid . "'";
echo $getmessages;
$messages = mysql_query($getmessages);
if(mysql_num_rows($messages) != 0) {
$table = "<table><tr><th>From</th><th>Subject</th><th>Message</th></tr>";
while($results = mysql_fetch_array($messages)) {
if(strlen($results[message]) < 30){
$message = $results[message];
}
else {
$message = substr($results[message], 0 ,30) . "...";
}
if($results[msgread] == 0){
$table .= "<tr style='background:#9CFFB6'>";
$table .= "<td>" . $results[from] . "</td><td>" . $results[subject] . "</td><td><a href='viewmessage.php?id=" . $results[message_id] ."'>" . $message . "</a></td></tr>";
}
else {
$table .= "<tr>";
$table .= "<td>" . $results[from] . "</td><td>" . $results[subject] . "</td><td><a href='viewmessage.php?id=" . $results[message_id] ."'>" . $message . "</a></td></tr>";
}
}
echo $table ."</table>";
}
else {
echo "No Messages Found";
}
There's all the code, including grabbing the info from the database. Thanks.

if(strlen($results[message]) < 30){
the message probably should be quoted:
if(strlen($results['message']) < 30){
There are quite a few other similar issues

i tested your code an the only mistake i found was the lack of quoatation marks in the indices array $results. You are using this $result[message_id] when the most appropriate would be $result['message_id']. The rest works as expected, the records with msgread equal to 0 stayed with the green line.

Your code looks a little nasty and is not easy to read.
You should use mysqli_fetch_assoc().
Always end style with a ;
use quotation on associative array
more logic choice of var names
where does $userid come from? is the content safe?
Here is quickly cleaned version of your code :
$query = "SELECT * FROM messages WHERE toperson = '" . $userid . "'";
if($results = mysqli_query($query)) {
if(mysqli_num_rows($results) != 0) {
$table = "<table><tr><th>From</th><th>Subject</th><th>Message</th></tr>";
while($data = mysqli_fetch_assoc($results)) {
if(strlen($data['message']) > 30){
$data['message'] = substr($data['message'], 0 ,30) . "...";
}
$table .= "<tr";
if($data['msgread'] == 0){
$table .= " style='background:#9CFFB6;'";
}
$table .= ">";
$table .= "<td>" . $data['from'] . "</td><td>" . $data['subject'] . "</td><td><a href='viewmessage.php?id=" . $data['message_id'] ."'>" . $data['message'] . "</a></td></tr>";
}
echo $table ."</table>";
} else {
echo "No Messages Found";
}
}

Related

Never Displays the first row

When I run the code in $Date within phpmyadmin it returns the correct number of rows but on the page it will never display the first row for some reason and I know it is not the numbering being off because my laptop Id is different for the two rows
function select_History_Date($link){
$status = '';
$i = 1;
$date = "SELECT Student_Id, Loaner_Laptop_Id, HDD_Id, "
. "Phone_Id, date_returned "
. "FROM equipment_history WHERE Loaner_Laptop_Id "
. "IS NOT NULL OR HDD_Id IS NOT NULL OR Phone_Id IS NOT NULL";
$ret = mysqli_query($link, $date);
$row1 = mysqli_fetch_array($ret, MYSQLI_ASSOC);
if (!$ret) {
die('Could not execute select statement:' . mysqli_errno($link));
} else {
while ($row1 = mysqli_fetch_array($ret, MYSQLI_ASSOC)) {
$status .= '<tr>';
$status .= '<td>' . $i . '</td>';
if (is_null($row1['date_returned']) && is_null($row1['HDD_Id']) && is_null($row1['Phone_Id'])){
$status .= '<td><a href="ReturnLaptop.php?laptopId=' .
$row1['Loaner_Laptop_Id'] . '&studentId='.
$row1['Student_Id']. '">'. 'Return'. '</td>';
} elseif (is_null($row1['date_returned']) && is_null($row1['HDD_Id']) && is_null($row1['Loaner_Laptop_Id'])){
$status .= '<td><a href="ReturnPhone.php?phoneId=' .
$row1['Phone_Id'] . '&studentId='.
$row1['Student_Id']. '">'. 'Return'. '</td>';
}elseif (is_null($row1['date_returned']) && is_null($row1['Phone_Id']) && is_null($row1['Loaner_Laptop_Id'])){
$status .= '<td><a href="ReturnHDD.php?hddId=' .
$row1['HDD_Id'] . '&studentId='.
$row1['Student_Id']. '">'. 'Return'. '</td>';
}else{
$status .= '<td>' . $row1['date_returned'] . '</td>';
}
$status .= '</tr>';
$i++;
return $status;
}
}
}
This line:
$row1 = mysqli_fetch_array($ret, MYSQLI_ASSOC);
is reading the first row of data from your result. But then you are not doing anything with it before you do
while ($row1 = mysqli_fetch_array($ret, MYSQLI_ASSOC)) {
which overwrites the data with the values from the second row. You need to delete the first line.

Else statement doesn't work in option select

I am trying to implement a dropdown search option. All my search results are working. All the commands that I have assigned to if statements work, but when it does to else it deosn't work.
Here is my code:
if(isset($_REQUEST['submit'])){
$opt = $_POST['opt'];
if($opt==1){//if opt = 1
$sqle = "SELECT * FROM tbl_events WHERE title LIKE '%{$keywords}%'";
$resulte = mysql_query($sqle,$con) or die(mysql_error());
while($row=mysql_fetch_array($resulte)){
echo "<h4>" . $row['title'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}else if($opt==2){//if opt = 2
$sqls = "SELECT * FROM tbl_games WHERE games_name LIKE '%{$keywords}%'";
$results = mysql_query($sqls,$con)or die(mysql_error());
while($row=mysql_fetch_array($results)){
echo "<h4>" . $row['games_name'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}else{
echo "Your Searched keyword did not match";
}
}
What to do?
Try this: Take a flag to check if record exists.
$flag = false;
if($opt==1){//if opt = 1
$sqle = "SELECT * FROM tbl_events WHERE title LIKE '%{$keywords}%'";
$resulte = mysql_query($sqle,$con) or die(mysql_error());
if(mysql_num_rows($resulte) > 0) {
$flag = true;
while($row=mysql_fetch_array($resulte)){
echo "<h4>" . $row['title'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}
}else if($opt==2){//if opt = 2
$sqls = "SELECT * FROM tbl_games WHERE games_name LIKE '%{$keywords}%'";
$results = mysql_query($sqls,$con)or die(mysql_error());
if(mysql_num_rows($resulte) > 0) {
$flag = true;
while($row=mysql_fetch_array($results)){
echo "<h4>" . $row['games_name'] . "</h4><br/>";
echo "<p>" . $row['description'] . "<p>";
}
}
}
if(!$flag){
echo "Your Searched keyword did not match";
}

Warning: Invalid argument supplied for foreach() in /path/time/processing/time/viewpunlist.php on line 54

I am trying to get this php code to run. I have made it output the table, however, I am getting this error:
Warning: Invalid argument supplied for foreach() in /path/time/processing/time/viewpunlist.php on line 54
I have been able to use the $row to get the values of it before and even reassigned it later to make sure that it wasn't only executing in WHILE. I have no clue what is going on there. Line 54 is the line:
foreach ( $row as $each)
Here is the file that I am using it in. Any help is appreciated on
a) how to make this file better and
b) getting the whole foreach statement working.
Thank you in advance!
<head>
<title>View My Punches</title>
<body bgcolor="#9966FF">
<link rel="icon" type="image/ico" href="http://example.com/time/favicon.ico"/>
</head>
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define('DB_NAME', 'name');
define('DB_USER', 'user');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'host');
$link = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($link->connect_errno > 0){
die('Could not connect: ' .connect_error());
}
$userid_value = $_POST['userid'];
$table = "tc_".$userid_value;
$checkusersql = "SELECT * FROM tc_users WHERE userid = '$userid_value'";
$usercheck = $link->query($checkusersql);
$punchessql = "SELECT * FROM $table ORDER BY id";
$result = $link->query($punchessql);
$unixtime = time() + 60*60;
$time_value = date("h:i:s A", $unixtime);
$date_value = date("m/d/Y", $unixtime);
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
echo "Punch Report for " . $userid_value . " | Generated at " . $time_value . " on " . $date_value;
echo "<p></p>";
if ($result->num_rows == 0) {
echo "<p></p>";
echo "No punches were found for " . $userid_value . ".";
}else{
echo "<table border=1>";
echo "<tr><th>Punch ID</th><th>Time</th><th>Punch Type</th><th>Group</th><th>Department</th><th>Notes</th></tr>";
while ($row = $result->fetch_array())
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['time'] . "</td><td>" . $row['punchtype'] . "</td><td>" . $row['groupname'] . "</td><td>" . $row['dept'] . "</td><td>" . $row['notes'] . "</td>";
}
echo "</table>";
}
}
$differs = array();
$inout = array();
$inarray = array();
$outarray = array();
$current = array('in'=>$inarray,'out'=>$outarray,'length'=>'');
foreach ( $row as $each)
{
if ( $each['punchtype'] == 'in' )
{
if ( empty($current['in']) )
{ $current['in'] = $each; }
}
else if ( $each['punchtype'] == 'out' )
{
if ( empty($current['out']) )
{ $current['out'] = $each; }
}
if (( !empty($current['in']) && !empty($current['out'])))
{
$in = new DateTime($current['in']);
$out = new DateTime($current['out']);
$current['length'] = $in->diff($out);
$inout[] = $current;
$stamp = $inout['length'];
$stampformat = $stamp->format('%s');
$stampint = intval($stampformat);
$stampintval = $stampint/3600;
echo $stampintval;
}
}
?>
&nbsp
&nbsp
<form method="GET" action="http://example.com/time/panel.php">
<input type="submit" value="Go Home">
</form>
You need to check if the argument passed through foreach is an array.
This can be done by using the function is_array()
if (is_array($variable)) {
foreach ($variable as $item) {
}
}
Unless I am missing something, which I do a lot, it seems to me that you've already iterated through your SQL results here,
if ($usercheck->num_rows == 0) {
echo "Sorry, " . $userid_value . " is not a valid user ID. Please try again.";
}else {
echo "Punch Report for " . $userid_value . " | Generated at " . $time_value . " on " . $date_value;
echo "<p></p>";
if ($result->num_rows == 0) {
echo "<p></p>";
echo "No punches were found for " . $userid_value . ".";
}else{
echo "<table border=1>";
echo "<tr><th>Punch ID</th><th>Time</th><th>Punch Type</th><th>Group</th><th>Department</th><th>Notes</th></tr>";
while ($row = $result->fetch_array())
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['time'] . "</td><td>" . $row['punchtype'] . "</td><td>" . $row['groupname'] . "</td><td>" . $row['dept'] . "</td><td>" . $row['notes'] . "</td>";
}
echo "</table>";
}
}
which means that the data is no longer available because you are not using a prepared statement in order to reuse it. You should be able to run another query for the foreach.
$punchessql = "SELECT * FROM $table ORDER BY id";
$result = $link->query($punchessql);
$row = $result->fetch_array();
foreach ( $row as $each) {
//your existing code.
}

printing [mysql_query] result in a table

I want to print mysql_query result in a table. I know how to do it but I am just confused. I tried this.
<?php
mysql_connect("localhost","root","") or die("Could not Connect.");
mysql_select_db("check") or die("Could not Select DB");
$table = "cc";
$i = 1;
$query = "select * from $table";
$sql = mysql_query($query);
if($sql){
echo "<table border='5'><tr>";
while($i<=2 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=4 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=6 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
while($i<=8 && $row = mysql_fetch_array($sql)){
echo "<td>" . $row[id] . " : " . $row[name] . "</td>";
++$i;
}
echo "</tr><tr>";
echo "</tr></table>";
}
?>
As you can see it is written again and again with a slight change of 2,4,6,8 in the while loop. It works but the problem is I cant rewrite it again and again as when the website will go live it will have more than 1000 entries. Could You guys help me out by suggesting another way to do this?
""** I need it to be like these dots (dots represent records in the database) **"""
. . . .
. . . .
. . . .
THANKS in Advance.
Ramzy
<?php
mysql_connect("localhost","root","") or die("Could not Connect.");
mysql_select_db("check") or die("Could not Select DB");
$table = "cc";
$query = "select * from $table";
$sql = mysql_query($query);
if($sql){
echo "<table border='5'><tr>";
while($row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
echo "</tr></table>";
}
?>
while($row = mysql_fetch_array($sql)) {
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
I don't really see what's the problem here.
By the way you should never call you're array like this $row[id] but you should quote the key instead $row['id']; Because if a constant id exists it will screw up your code and also for performance reason.
Just use
$limit = 1000;//place any value you need here to limit the number of rows displayed
while ($i<=$limit && $row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
++$i;
}
Also, that limit is unnecessary if all you want is to flush every record to the output. You could just do
while ($row = mysql_fetch_array($sql)){
echo "<td>" . $row['id'] . " : " . $row['name'] . "</td>";
}
And it will stop as soon as there are no more records.
To print all database rows into an HTML-table, use:
echo '<table>';
$i = 0; // $i is just for numbering the output, not really useful
while($row = mysql_fetch_array($sql))
{
echo '<tr><td>' . $i . ' - ' . $row['id'] . ' : ' . $row['name'] . '</td></tr>';
$i++;
}
echo '</tr></table>';
here is a general function I use:
function query_result_to_html_table($res, $table_id = NULL, $table_class = NULL, $display_null = true)
{
$table = array();
while ($tmp = mysql_fetch_assoc($res))
array_push($table, $tmp);
if (!count($table))
return false;
echo "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" "
. ($table_id ? "id=\"$table_id\" " : "")
. ($table_class ? "class=\"$table_class\" " : "") . ">";
echo "<tr>";
foreach (array_keys($table[0]) as $field_name) {
echo "<th>$field_name";
}
foreach ($table as $row) {
echo "<tr>";
foreach ($row as $col => $value) {
echo "<td>";
if ($value === NULL)
echo "NULL";
else
echo $value;
}
echo "\n";
}
echo "</table>\n";
return true;
}
I Got The Answer.. I wanted it to be like this. I made this and It Actually Works.
<?php
$i = 1;
mysql_connect("localhost" , "root" , "") or die('Could not Connect.');
mysql_select_db("db") or die('Could not select DB.');
$query = "select * from `check`";
$sql = mysql_query($query) or die(mysql_error());
echo "<table border='5' width='50%'><tr><th>Name</th><th>Gender</th></tr></table><table border='5' width='50%'><tr>";
if($i<3){
echo "<td align='center'>".$row['name']."</td>";
echo "<td align='center'>".$row['gender']."</td>";
++$i;
} else {
echo "<td align='center'>".$row['name']."</td><td align='center'>".$row['gender']."</td>";
echo "</tr>";
$i = 1;
echo "<tr>";
}
}
echo "</table>";
?>
</div>
Thank You Guys For Your Support

php while() loop within if / else not seeming to work

I've been confused about why this wont work! My query executes perfectly fine in all aspects, but when I added the if check on the $row value, the echo message goes as expected (if there are no results), but the else will not kick when there is a match in my query??? Why is this not working? Someone please ease my pain and set me straight!!
$row = mysql_fetch_array($result);
if (!$row) {
echo "Sorry brah. Nothing matches your search criteria.";
} else {
$i = 1;
while($row = mysql_fetch_array($result)) {
echo "$i - " . $row['first_name'] . " " . $row['last_name'] . " - " . $row['address'] . "<br />";
$i++;
}
}
$row = mysql_fetch_array($result); // this fetches the first row your result
...
in while loop you are again fecthing thr row from result. Which will not work if you have only one row in resul
use
if (mysql_num_rows($result) == 0) {
echo "Sorry brah. Nothing matches your search criteria.";
} else {
$i = 1;
while($row = mysql_fetch_array($result)) {
echo "$i - " . $row['first_name'] . " " . $row['last_name'] . " - " . $row['address'] . "<br />";
$i++;
}
}
try mysql_num_rows($result)==0 instead in the if statement

Categories