I'm trying to create a internal messaging system.
My code is below:
$useraccess = $loggedInUser->username;
$sql = "SELECT id, user_name FROM ".$db_table_prefix."users WHERE user_name='$useraccess'";
$query = $mysqli->query($sql) or die ("Error");
while ($row = mysqli_fetch_array($query)) {
$pid = $row["id"];
$username = $row["user_name"];
}
$query->close();
$sqlCommand = "SELECT COUNT(id) AS numbers FROM ".$db_table_prefix."messages_inbox WHERE userid='$pid'";
$query = $mysqli->query($sql) or die ("Error");
$result = mysqli_fetch_assoc($query);
$inboxMessages = $result['numbers'];
?>
<h1>Inbox</h1>
<?php
$sql="SELECT * FROM ".$db_table_prefix."messages_inbox WHERE userid='$pid' ORDER by id DESC";
$result=$mysqli->query($sql);
$count=mysqli_stmt_num_rows($result);
?>
<p>
<table width="500" border="0" cellspacing="0" cellpadding="0">
<tr>
<th style="text-align: left; ">Title</th>
<th style="text-align: right; ">Sender</th>
<th style="text-align: right; "><b>Actions</b></th>
</tr>
<?php
while($rows=mysqli_field_count($result)) {
?>
<?php if ($rows['viewed'] == 0) { // show messages in bold?>
<tr>
<td style="text-align: left; "><b><?php echo $rows['title']; ?></b></td>
<td style="text-align: right; "><?php echo $rows['from_username']; ?></td>
<td style="text-align: right; ">Delete</td>
</tr>
<?php } else if ($rows['viewed'] == 1) { ?>
<tr>
<td style="text-align: left; "><?php echo $rows['title']; ?></td>
<td style="text-align: right; "><?php echo $rows['from_username']; ?></td>
<td style="text-align: right; ">Delete</td>
</tr>
<?php } ?>
<?php } ?>
</table>
<?php if ($inboxMessages > 0) { ?>
<?php } else
{ print "<div id=\"errors\">Currently you do not have messages in your Inbox</div>";
} ?>
This is the inbox in which I'm trying to show data from the DB. It connects no problem otherwise it would throw up the Error, so I believe it's my syntax.
I receive the following errors.
Warning: mysqli_stmt_num_rows() expects parameter 1 to be mysqli_stmt, object given in /opt/lampp/htdocs/project/inbox.php on line 28
Warning: mysqli_field_count() expects parameter 1 to be mysqli, object given in /opt/lampp/htdocs/project/inbox.php on line 38
Notice: Undefined index: numbers in /opt/lampp/htdocs/project/inbox.php on line 20
Use mysqli_num_rows instead, as follows:
$count=mysqli_num_rows($result);
Reference documentation: http://php.net/manual/en/mysqli-result.num-rows.php
To use mysqli_stmt_num_rows you need to change a few lines from what you have:
$sql="SELECT * FROM ".$db_table_prefix."messages_inbox WHERE userid='$pid' ORDER by id DESC";
if ($stmt = $mysqli->prepare($sql)) {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$count = mysqli_stmt_num_rows($stmt)
$stmt->close();
}
And here is the documentation for mysqli_stmt_num_rows: http://php.net/manual/en/mysqli-stmt.num-rows.php
Related
I'm trying to export the table (filtered) from MySQL to pdf.
The main problem here is that it only prints the last result on the list, instead of printing all the results.
I have tried other code but I still get the same result. I don't know what is wrong with my code:
<?php
include("configsample.php");
?>
<?php
$string=$_GET['string'];
$course=$_GET['course'];
$category=$_GET['category'];
$from=$_GET['from'];
$to=$_GET['to'];
if ($_REQUEST["string"]<>'') {
$search_string = " AND restu_title LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%'";
}
if ($_REQUEST["course"]<>'') {
$search_course = " AND restu_course='".mysql_real_escape_string($_REQUEST["course"])."'";
}
if ($_REQUEST["category"]<>'') {
$search_category = " AND category='".mysql_real_escape_string($_REQUEST["category"])."'";
}
if ($_REQUEST["from"]<>'' and $_REQUEST["to"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE restu_year BETWEEN '".mysql_real_escape_string($_REQUEST["from"])."' AND '".mysql_real_escape_string($_REQUEST["to"])."'".$search_string.$search_course;
} else if ($_REQUEST["from"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE restu_year = '".mysql_real_escape_string($_REQUEST["from"])."'".$search_string.$search_course;
} else if ($_REQUEST["to"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE restu_year = '".mysql_real_escape_string($_REQUEST["to"])."'".$search_string.$search_course;
} else {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE restu_id>0".$search_string.$search_course.$search_category;
}
$html='<table>
<tr style="color:#010101; font:bold 13px Times New Roman; height:40px;">
<th>Research Title</th>
<th>Year</th>
<th>Proponent(s)</th>
<th>Adviser</th>
<th>Research Panel</th>
</tr>';
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)){
$html2='<tr>
<td style="padding:10px;">'.$row['restu_title'].'</td>
<td style="padding:10px;">'.$row['restu_year'].'</td>
<td style="padding:10px;">'.$row['restu_by'].'</td>
<td style="padding:10px;">'.$row['restu_ad'].'</td>
<td style="padding:10px;">'.$row['restu_panel'].'</td>
</tr>
</table>';
}
}
include("mpdf60/mpdf.php");
$mpdf=new mPDF('c','Letter','','',20,20,18,16,9,9,'L');
$mpdf->SetDisplayMode('fullpage');
$mpdf->AddPage('L');
$mpdf->WriteHTML($html);
$mpdf->WriteHTML($html2);
$mpdf->Output();
exit;
?>
You need to concatenate your text string to avoid $html2 to be overwritten by the next value.
Everytime the loop is running, $html2 is overwritten with the new value. In your case, you need to add a dot just before the equal symbol:
while ($row = mysql_fetch_assoc($sql_result)){
$html .='<tr>
<td style="padding:10px;">'.$row['restu_title'].'</td>
<td style="padding:10px;">'.$row['restu_year'].'</td>
<td style="padding:10px;">'.$row['restu_by'].'</td>
<td style="padding:10px;">'.$row['restu_ad'].'</td>
<td style="padding:10px;">'.$row['restu_panel'].'</td>
</tr>';
}
Be careful to correctly place the </table>. If your SQL request has no result, the table will not be closed, rendering the HTML invalid.
You need to do it like this:
$html='<table>
<tr style="color:#010101; font:bold 13px Times New Roman; height:40px;">
<th>Research Title</th>
<th>Year</th>
<th>Proponent(s)</th>
<th>Adviser</th>
<th>Research Panel</th>
</tr>';
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)){
$html .='<tr>
<td style="padding:10px;">'.$row['restu_title'].'</td>
<td style="padding:10px;">'.$row['restu_year'].'</td>
<td style="padding:10px;">'.$row['restu_by'].'</td>
<td style="padding:10px;">'.$row['restu_ad'].'</td>
<td style="padding:10px;">'.$row['restu_panel'].'</td>
</tr>';
}
}
$html .= '</table>';
append $html2. You are assigning value in loop so it displaying only last record.
Use like this..
$html2=$html2.'<tr>
<td style="padding:10px;">'.$row['restu_title'].'</td>
<td style="padding:10px;">'.$row['restu_year'].'</td>
<td style="padding:10px;">'.$row['restu_by'].'</td>
<td style="padding:10px;">'.$row['restu_ad'].'</td>
<td style="padding:10px;">'.$row['restu_panel'].'</td>
</tr>';
This question already has answers here:
Checking if mysqli_query returned any values?
(2 answers)
Closed 1 year ago.
I have a report, which has a few prompts, and based on the prompt selection, sometimes there might be no records in the report. In such cases, I want to show a message NO RECORDS FOUND on the Cover Page.
Can anyone tell me how I do this?
<?php
error_reporting(0);
include("connection.php");
session_start();
if(!($_SESSION['email']))
{
echo "please login first to access this page";
header("refresh:3;url=index.php");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
body
{
margin: 0;
padding: 0;
}
table
{
border-collapse: collapse;
width: 100%;
font-family: sans-serif;
font-size: 15px;
}
th,td
{
padding: 5px;
text-align: left;
}
tr:nth-child(even)
{
background: #edf0f5;
}
th
{
background: #00A800;
color: white;
padding: 5px;
font-family: sans-serif;
}
a
{
text-decoration: none;
color: #00A800;
}
a:hover
{
text-decoration: underline;
}
</style>
<title>View all the data</title>
</head>
<body>
<table>
<tr>
<th>Roll NO</th>
<th>Student Name</th>
<th>Father Name</th>
<th>Class</th>
<th>Class Section</th>
<th>Phone number</th>
<th>Email Address</th>
<th>Address</th>
<th>Edit</th>
<th>View Fees</th>
<th>Attendance</th>
</tr>
<?php
$select="select *from student where class='1' AND section='B' ";
$run=mysqli_query($con,$select);
$i=0;
while($row=mysqli_fetch_array($run))
{
$id=$row['id'];
$s_name=$row['s_name'];
$f_name=$row['f_name'];
$class=$row['class'];
$section=$row['section'];
$phone=$row['phone'];
$email=$row['email'];
$address=$row['address'];
$i++;
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $s_name;?></td>
<td><?php echo $f_name;?></td>
<td><?php echo $class;?></td>
<td><?php echo $section;?></td>
<td><?php echo $phone;?></td>
<td><?php echo $email;?></td>
<td><?php echo $address;?></td>
<td>Edit</td>
<td>Fees</td>
<td>Attendance</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
You can use mysqli_num_rows() to check the number of rows in a result
$select = "select *from student where class='1' AND section='B' ";
$run = mysqli_query($con, $select);
if (mysqli_num_rows($run > 0)) {// check if your query return result
// your code
} else {
echo "NO result found";
}
Read http://php.net/manual/en/mysqli-result.num-rows.php
You need to check if rows are returned, if not, show error.
$i = 0;
while($row=mysqli_fetch_array($run)) {
// Your code
$i++;
}
if ($i <1) {
?>
<tr><td colspan="11">There are no records.</td></tr>
<?php
}
Explanation:
1) We have taken a variable $i, initialized to 0
2) In while loop, it is incremented.
3) If we have records, after while loop, we will get $i more than 0.
4) If it is still 0 that is less than 1, it means there are no records and show the error message.
You can use mysqli_num_rows to count the number of rows returned:
Returns the number of rows in the result set.
Since, mysqli_num_rows will return 0 if there's no result, you can use ! to check if the result is false.
$select="select *from student where class='1' AND section='B' ";
$run=mysqli_query($con, $select);
if (!mysqli_num_rows($run)) {
echo "No result is found";
} else {
// to do if there's result
}
I have a table set up called Modules, that once a user is logged in it brings up the modules related to that user, this works fine. At the side of each module in the table I have a lessons link. once the user clicks on that I want it to display the lessons based on the module ID.
Any help would be great full.
My Module code in case I need to add something to it is as follows;
<?
include('../inc/security.inc.php');
authorise();
// Include databse connection file
include('../inc/connection.inc.php');
// Connect to the database
connect();
$userID = $_SESSION['userID'];
$sql = "SELECT * FROM tblModule WHERE userID = '$userID'" ;
$result = #mysql_query($sql) or die(mysql_error());
?>
and displaying the module table as follows;
<?php
// run a while loop through all records and create a new row for each one
while ($record = mysql_fetch_object($result))
{
?>
<table class="myTable">
<th class="col">Module ID</th>
<th class="col">Module Title</th>
<th class="col">Module Description</th>
<th class="col">User ID</th>
<th class="col">Manage</th>
</tr>
<tr class="row">
<td class="cell"><?php echo $record->moduleID; ?></td>
<td class="cell"><?php echo $record->moduleTitle; ?></td>
<td class="cell"><?php echo $record->moduleDescription; ?></td>
<td class="cell"><?php echo $record->userID; ?></td>
<td class="cell">Lessons</td>
</tr>
</table>
<?
}
// clean up after ourselves by cleating $result and closing the database connection
mysql_free_result($result);
mysql_close();
?>
Then so far in the lesson table i have;
<?
include('../inc/security.inc.php');
authorise();
// Include databse connection file
include('../inc/connection.inc.php');
// Connect to the database
connect();
$moduleID = $_SESSION['moduleID'];
$sql = "SELECT * FROM tblLessons WHERE moduleID = '$moduleID'" ;
$result = #mysql_query($sql) or die(mysql_error());
?>
With the result been displayed as;
<?php
// run a while loop through all records and create a new row for each one
while ($record = mysql_fetch_object($result))
{
?>
<table class="myTable">
<th class="col">LessonID</th>
<th class="col">Lesson Number</th>
<th class="col">Lesson Description</th>
<th class="col">ModuleID</th>
<th class="col">Lesson Plan ID</th>
<th class="col">Manage</th>
</tr>
<tr class="row">
<td class="cell"><?php echo $record->lessonID; ?></td>
<td class="cell"><?php echo $record->lessonNumber; ?></td>
<td class="cell"><?php echo $record->lessonDescription; ?></td>
<td class="cell"><?php echo $record->moduleID; ?></td>
<td class="cell"><?php echo $record->lessonPlanID; ?></td>
</tr>
</table>
<?
}
// clean up after ourselves by cleating $result and closing the database connection
mysql_free_result($result);
mysql_close();
?>
You're passing the moduleID as a query string variable to lessons.php, but in lessions.php you're looking for it in session data.
$moduleID = $_SESSION['moduleID'];
Try:
$moduleID = isset($_GET['moduleID']) ? $_GET['moduleID'] : false;
if ( $moduleID ) {
$sql = sprintf('SELECT * FROM tblLessons WHERE moduleID = %d', $moduleID);
$result = #mysql_query($sql) or die(mysql_error());
} else {
// No moduleID, so show an error message, redirect user, or the like
}
Note that I'm using sprintf so that $moduleID is converted to a digit. The code you're using - passing the value directly to MySQL - is dangerous. Google: "sql injection".
If $moduleID can in fact be a string, then you need to take extra steps to ensure that the data is sanitized before being passed to MySQL, e.g.
$moduleID = isset($_GET['moduleID']) ? $_GET['moduleID'] : false;
if ( $moduleID ) {
$sql = sprintf("SELECT * FROM tblLessons WHERE moduleID = '%s'", mysql_real_escape_string($moduleID));
$result = #mysql_query($sql) or die(mysql_error());
} else {
// No moduleID, so show an error message, redirect user, or the like
}
You should also consider switching to PDO, as the mysql_ functions are depreciated. PDO is a much easier, safer way to interact with MySQL.
I have set up an 'orders' page that should be pretty straight-forward, requiring a for each loop to generate past orders from the DB. Within each loop, there needs to be an explode to separate each item(,), then another explode to pull the details out of each item(-). I was wondering if anyone could tell me why I'm getting the error message "Warning: mysql_num_rows() expects parameter 1" at the end of each iteration of my foreach loop? It's particularly confusing for me because the code still works, which I don't think it should if the error was true.
<?php
$sql = "SELECT * FROM orders WHERE store='$user'";
$res = mysql_query($sql);
$arrOrders = array();
while ($row = mysql_fetch_array($res)) {
array_push($arrOrders, $row);
}
?>
<table width="85%" align="center" border="0" cellpadding="5">
<?php if (count($arrOrders) > 0) { ?>
<?php foreach ($arrOrders as $key => $value) { ?>
<tr>
<td valign="top" style="font-weight: bold">
ID #<?=$value['id']?>
</td>
<td valign="top" style="font-weight: bold">
Status: <?=$value['status']?>
</td>
<td valign="top" style="font-weight: bold">
Order #<?=$value['order_ref']?>
</td>
<td align="left" valign="top" style="font-weight: bold">
<?php
$tmpProds = explode(',', $value['products']);
foreach ($tmpProds as $key2 => $value2) {
$tmpProdInfo = explode('-', $value2);
$sql2 = 'SELECT * FROM products_full WHERE id = ' . $tmpProdInfo[0];
$res2 = mysql_query($sql2);
if (mysql_num_rows($res2) > 0) { // THIS IS THE ROW THAT THE ERROR MESSAGE POINTS TO
echo $tmpProdInfo[1] + $tmpProdInfo[2] . ' x ' . mysql_result($res2, 0, 'alpha_code') . ' (' . trim(mysql_result($res2, 0, 'description')) . ')<br /><br />';
}
}
?>
</td>
</tr>
<tr>
<td width="100%" colspan="5" align="center">
<hr style="width: 100%" />
</td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td width="100%" align="center">
There are currently no complete orders.
</td>
</tr>
<?php } ?>
</table>
Thanks in advance, I think I've included everything that is relative but if anything else is needed please let me know.
Joe
Try this:
$sql2 = 'SELECT * FROM products_full WHERE id = '.$tmpProdInfo[1].'';
if (count($res2) > 0)
Also, be aware when you want to use MySQL_num_rows you should include the connection. see the manual:
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
I have a results page and I would like there to be a bit at the top of the page where it says how many results were returned. How do I do this?
My code is
<?php
if(strlen(trim($_POST['search'])) > 0) {
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
mysql_connect ("3", "", "");
mysql_select_db ("");
if (!empty($_POST["search_string"]))
{
}
$query = "SELECT name,location,msg FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result) {
while ($row = mysql_fetch_array ($result)) { ?>
<center>
<table height="20" width="968" cellpadding="0" cellspacing="0">
<tr>
<td>
<table height="20" width="223" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="#045FB4"><?php echo $row[0]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
<td>
<table height="20" width="745" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="black"><?php echo $row[1]; ?>
<?php echo $row[2]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
<td align="right">
<font face="helvetica" size="2" color="red">See More...</font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
</tr>
</table>
<?php
}
}
}
?>
</center>
THANKS!
James
If you're going to keep it to one page then mysql_num_rows() will do the trick and you're good to go. If you use pagination on the other hand, then your SELECT query will have a LIMIT clause and a second query can be constructed using COUNT(*) on the same tables with the same WHERE clause.
$total_query = "SELECT COUNT(*) FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'"
I’m not trying to compete with the other fine answers. I’m posting this as an answer because it’s too big for a comment.
Since you asked in a comment what could be done to improve your HTML, I refactored your code a bit just to illustrate some things you could do. I also included mysql_num_rows($result) mentioned by the others for the sake of completion.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample</title>
<style type="text/css">
table {
font-family: helvetica;
font-size: small;
width: 968px;
}
td {
border-bottom: 1px solid #e6e6e6;
}
.name {
color:#045FB4;
}
.msg {
color:black;
}
.more {
color:red;
}
</style>
</head>
<body>
<?php
if(strlen(trim($_POST['search'])) > 0):
$search = mysql_real_escape_string($_POST["search"]);
$searchterm = mysql_real_escape_string($_POST["searchterm"]);
mysql_connect ("localhost", "root", "");
mysql_select_db ("sample");
if (!empty($_POST["search_string"]))
{
$search_string = mysql_real_escape_string($_POST["search_string"]);
// more code here
}
$query = "SELECT name,location,msg FROM contact
WHERE name LIKE '%$search%'
AND location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result):
$num_rows = mysql_num_rows($result);
?>
<p>Found <?php echo $num_rows; ?> results.</p>
<table>
<?php
while ($row = mysql_fetch_array ($result)):
?>
<tr>
<td class="name"><?php echo $row['name']; ?></td>
<td class="msg"><?php echo $row['location'], ' ', $row['msg']; ?></td>
<td class="more">See More...</td>
</tr>
<?php
endwhile;
endif;
endif;
?>
</table>
</body>
</html>
Normally, I would put the CSS in a separate file, but this is only an example.
Some things to notice:
There’s only one table
There’s no style information in the HTML
It uses mysql_real_escape_string. Ideally you'd also want to use prepared statements, but I’ll leave that as a personal exercise for you. :)
Even this can be improved quite a bit, but it's a start.
Try using mysql_num_rows($query). I am no PHP expert but, from memory, that should do the trick. Just echo this wherever you want it.
$num_rows = mysql_num_rows($result);
Check out the documentation: http://php.net/manual/en/function.mysql-num-rows.php
Also you can use SQL_CALC_FOUND_ROWS and FOUND_ROWS():
$query = "SELECT SQL_CALC_FOUND_ROWS name,location,msg FROM contact WHERE name LIKE '%$search%' AND location LIKE '%$searchterm%'";
$result = mysql_query($query);
if ($result)
{
$rs_count = mysql_query("SELECT FOUND_ROWS();");
$counted = (int)mysql_result($rs_count, 0);
}