Im trying to order posts by their date, but whenever I try to do that I get this error:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\localhost\bootstrap\category.php on line 58
DATABASE STRUCTURE: http://puu.sh/1630b
<?php
//category.php
include 'connect.php';
//first select the category based on $_GET['cat_id']
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories
WHERE
cat_id = " . mysql_real_escape_string($_GET['id']);
$result = mysql_query($sql);
if(!$result)
{
echo 'The category could not be displayed, please try again later.' . mysql_error();
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'This category does not exist.';
}
else
{
//display category data
while($row = mysql_fetch_assoc($result))
{
echo '<h2>Topics in ′' . $row['cat_name'] . '′ category</h2><br />';
$title = $row['cat_name'];
include 'header.php';
}
//do a query for the topics
$sql = "SELECT
topic_id,
topic_subject,
topic_date,
topic_cat
FROM
topics
ORDER BY
topic_date DESC
WHERE
topic_cat = " . mysql_real_escape_string($_GET['id']);
$result = mysql_query($sql);
// if(!$result)
// {
// echo 'The topics could not be displayed, please try again later.';
// }
// else
// {
if(mysql_num_rows($result) == 0)
{
echo 'There are no topics in this category yet.';
}
else
{
//prepare the table
echo '<table border="1" class="table table-bordered table-striped" style="float: right; width: 990px;">
<tr>
<th>Topic</th>
<th>Created at</th>
</tr>';
while($row = mysql_fetch_assoc($result))
{
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3>' . $row['topic_subject'] . '<br /><h3>';
echo '</td>';
echo '<td class="rightpart">';
echo date('d-m-Y', strtotime($row['topic_date']));
echo '</td>';
echo '</tr>';
echo '';
echo '';
}
echo '</table>';
echo '</div>';
}
// }
}
}
include('footer.php');
?>
I this case the problem will be in the commented lines 52 - 57 which are supposed to check if the mysql_query has been successful. Your query fails and returns false (boolean), which is a valid return value.
The error itself depends on your database table structure (isn't part of your link).
Your query that executes, fails and returned a boolean instead of a resource!
build in some error handling in your script.
do not use mysql_ functions, they are deprecated.
And now that you have edited your post, it is obvious that the ORDER BY comes after the WHERE.
Related
This are my db table:
But my query only get 1 row for each table like this:
As you can see, there are 2 tables for 1003 because it has 2 rows. It should be only one (1) table of 1003 with 2 rows. How do I fix this? EXPECTED RESULT:
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone GROUP BY model";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row["model"]?></td>
</tr>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
You have at least 5 problems here,
[edit: problem 1 removed & changed sample based on extended answer]
Inside your while { ... } loop, you're printing an entire table, when you should only be printing the <tr>...</tr> part there. This is what causes additional table(s).
And 3rd problem: your "no_record" line is a loose <td>. Not only isn't it inside the table (which is covered in problem #2), it's also not wrapped with a <tr>.
4th problem: You're randomly printing the echo $row["brand_code"] outside of the table.
5th problem: you're printing raw data from the database as if it is valid html, it more than likely is not. it has to be probably encoded with htmlentities/htmlspecialchars.
Quick & dirty fixed version:
function tableOpen($row) {
printf( '<h1>%s</h1>', htmlentities($row["brand_code"]) );
echo '<table id="table_stock" class="">';
echo '<thead>';
echo '<tr>';
echo '<th>Model</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
}
function tableClose() {
echo '</tbody>';
echo '</table><br>';
}
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone ORDER BY brand_code";
$lastBrand = null;
if ($result = mysqli_query($db, $query)) {
if (mysqli_num_rows($result) > 0) {
if ($lastBrand !== $row["brand_code"] && !is_null($lastBrand)) tableClose();
if ($lastBrand !== $row["brand_code"]) tableOpen($row);
$lastBrand = $row["brand_code"];
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
printf( '<td>%s</td>', htmlentities($row["model"]) );
echo '</tr>';
}
tableClose();
/// Free result
mysqli_free_result($result);
} else {
echo '<p class="no_record">No records found.</p>';
}
} else {
echo "ERROR: Not able to execute \$query: <br>" . htmlentities($query) . '<br>' . htmlentities(mysqli_error($link));
}
you need additional loop. Also in the first query you need to use group by codes.
$query = "SELECT model, brand_code FROM smartphone GROUP BY brand_code";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<?php
if ($result1 = mysqli_query($db, "SELECT DISTINCT model, brand_code FROM smartphone WHERE brand_code={$row["brand_code"]}"))
{
while ($row1 = mysqli_fetch_array($result1))
{
// get count for each model within brand_code
$cnt = ($result2 = mysqli_query($db, "SELECT COUNT(*) AS cnt FROM smartphone WHERE brand_code={$row["brand_code"]} AND model='{$row1["model"]}'")) && ($row2 = mysqli_fetch_array($result2)) ? $row2["cnt"] : "---";
?>
<tr>
<td><?php echo $row1["model"] ({$cnt})?></td>
</tr>
<?php
}
mysqli_free_result($result1);
}
?>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
I want this data to display all the results, in the query I get 129 results. But when I display it on the page I only get one row. I have used very similar code to get multiple results before, so I know it`s something simple, but I just can't get it. Any thoughts would be greatly appreciated!
<?php
$sql = "SELECT SUM(datamb) AS value_sum FROM maindata GROUP BY phonenumber";
$sql1 = "select dataplan as currentplan from maindata GROUP BY phonenumber";
$sql2 = "SELECT DISTINCT phonenumber AS value_sum1 FROM maindata";
$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 rows found, nothing to print so am exiting";
exit;
}
$result1 = mysql_query($sql2);
if (!$result1) {
echo "Could not successfully run query ($sql1) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result1) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
$result2 = mysql_query($sql2);
if (!$result2) {
echo "Could not successfully run query ($sql2) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result2) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)){
echo "<TABLE id='display'>";
echo "<td><b>Data Usage This Period: ". ROUND ($row["value_sum"],2) . "MB</b></td> ";
}
while ($row1 = mysql_fetch_assoc($result1)){
echo "<TABLE id='display'>";
echo "<td><b>Data Plan: ". $row1["currentplan"] . "</b></td> ";
}
while ($row2 = mysql_fetch_assoc($result2)){
echo "<TABLE id='display'>";
echo "<td><b>Phone Number: ". $row2["value_sum1"] . "</b></td> ";
}
?>
Updated based on suggestions - Very helpful thank you, I am very close, all values are correct but I can not get them in the same table, thoughts?
TRY To use ,
Loop in you code eg.
$result1 = mysql_query("SELECT DISTINCT phonenumber AS value_sum1 FROM maindata");
echo '<table>';
echo '<tr>';
echo '<th>id</th>';
echo '</tr>';
while($record = mysql_fetch_assoc($result))
{
echo '<tr>';
foreach ($record as $val)
{
echo '<td>'.$val.'</td>';
}
echo '</tr>';
}
echo '</table>';
Add
"LIMIT 0, 1" at the end of query
or
edit query like "select TOP 1 from....."
Lets make it easy on you ;)
have a look here how to use mysql_fetch_assoc
http://php.net/manual/en/function.mysql-fetch-assoc.php
follow the examples, you will be done in a sec.
I'm creating a small private forum to get some more knowledge about PHP/PDO etc. Now I have a weird bug/error/wrong piece of code that is not showing the echo. This is my code.
$sql2 = $db->prepare('SELECT topic_id, topic_subject,topic_date,topic_cat FROM topics WHERE topic_cat = :topid');
$sql2->bindParam(':topid', $_GET['id'], PDO::PARAM_INT);
$sql2->execute();
$result2 = $sql->rowCount();
if($result2 === FALSE){
echo 'The topics could not be displayed, please try again later.';
}
elseif ($result2 === 0){
echo 'There are no topics in this category yet.';
} else {
//prepare the table
echo '<table border="1">
<tr>
<th>Topic</th>
<th>Created at</th>
</tr>';
while($row = $sql2->fetch()) {
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3>' . $row['topic_subject'] . '<br /><h3>';
echo '</td>';
echo '<td class="rightpart">';
echo date('d-m-Y', strtotime($row['topic_date']));
echo '</td>';
echo '</tr>';
}
}
It should show the echo at while($row = $sql2->fetch()), but it is not. Also I know there is not enough { and } but that's because the other part of the code is not relevant.
You appear to count the rows returned by $sql then loop through $sql2. Have you checked to see if there are any results in $sql2?
I want to make this page secure, but i dont know where should i start. Because i've got injected yesterday I treid mysql escaping string, but i didn't help much. And i dont know anything about PDO, can you hook me up? Here's the code.
<?php
//category.php
require_once('startsession.php');
require_once('php/mysql_prisijungimas.php');
include 'connect.php';
//first select the category based on $_GET['cat_id']
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories
WHERE
cat_id = " . mysql_real_escape_string($dbc, trim($_GET['id']));
$result = mysql_query($sql);
if(!$result)
{
echo 'The category could not be displayed, please try again later.' . mysql_error();
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'This category does not exist.';
}
else
{
//display category data
while($row = mysql_fetch_assoc($result))
{
echo '<h2>Topics in ′' . $row['cat_name'] . '′ category</h2><br />';
}
//do a query for the topics
$sql = "SELECT
topic_id,
topic_subject,
topic_date,
topic_cat
FROM
topics
WHERE
topic_cat = " . mysql_real_escape_string($dbc, trim($_GET['id']));
$result = mysql_query($sql);
if(!$result)
{
echo 'The topics could not be displayed, please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
echo 'There are no topics in this category yet.';
}
else
{
//prepare the table
echo '<table border="1">
<tr>
<th>Topic</th>
<th>Created at</th>
</tr>';
while($row = mysql_fetch_assoc($result))
{
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3>' . $row['topic_subject'] . '<br /><h3>';
echo '</td>';
echo '<td class="rightpart">';
echo date('d-m-Y', strtotime($row['topic_date']));
echo '</td>';
echo '</tr>';
}
}
}
}
}
?>
In your case surround the mysql_real_escape_string with quotes like so:
SELECT * FROM table WHERE ID = '".mysql_real_escape_String($_POST['ID'])."'
Note the extra single quotes. This will make it more secure but nevertheless its better to use prepared statements. Besides prefering to use prepared statements over mysql_query, as of php version 5.5.0 the function mysql_query() will be deprecated.
There is another topic on stackoverflow which anwsers the question 'How to prevent SQL injection in PHP Pdo'. You might find some samples and extra information :
How can I prevent SQL injection in PHP?
How can I get the ID and title of a post in PHP? Each post has an ID and a title, and I need to be able to get both.
ID# Title
1013 Name
1025 Name
Your question is a bit unclear. Assuming you use MySQL, you can get the id and the title of a post like this:
<?php
$query = "SELECT id, title FROM table";
$result = mysql_query($query);
if(!$result)
{
echo 'The query failed.<br />';
echo mysql_error();
}
else
{
//check if there are results
if(mysql_num_rows($result) == 0)
{
echo 'No results.';
}
else
{
//loop through the results
while($row = mysql_fetch_assoc($result))
{
echo 'ID: ' . $row['id'] . ', name: ' . $row['title'];
}
}
}