SQL Selection not outputting data - php

Starting off, I'm kind of stumbling in the dark here with PHP/SQL, and don't really know how to bugtest that well, so forgive my vagueness about the exact nature of the problem. Moving on.
I have some code which grabs category ids, names, and descriptions from an SQL table, and saves the result to a variable. This is done through statement preparing to avoid an possibility of SQL injection. This value is then fed into some PHP which checks if the query had any response, and if so prints that into a table.
<?php
//create_cat.php
include_once (__DIR__ . '/../includes/db_connect.php');
include_once (__DIR__ . '/../includes/functions.php');
include_once (__DIR__ . '/header.php');
ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(-1);
$stmt = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
if (login_check($mysqli) == true) {
if(!$result = $mysqli->query($stmt)){
echo 'The categories could not be displayed, please try again later.';
} else {
if ($result->num_rows === 0) {
echo 'No categories defined yet.';
} else {
//prepare the table
echo '<table border="1">
<tr>
<th>Category</th>
<th>Last topic</th>
</tr>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3>' . $row['cat_name'] . '</h3>' . $row['cat_description'];
echo '</td>';
echo '<td class="rightpart">';
echo 'Topic subject at 10-10';
echo '</td>';
echo '</tr>';
}
}
}
} else {
echo <<<error
<p>
<span class="error">You are not authorized to access this page.</span> Please login.
</p>
error;
}
include_once (__DIR__ . '/footer.php');
?>
However, the table SQL table definitely has values, but the PHP is only outputting: "The categories could not be displayed, please try again later."

Ok, got it working. I removed $stmt_prep commands, made sure to only use mysqli commands, and fixed some syntax errors. Code still has broken HTML, but the problem I was asking about is fixed.

If you wanted to keep the object oriented style, the main mistake was closing the statement before fetching the results. PHP will free up the statement at the end of the script anyway, but once you've called $stmt->close(); you won't be able to read any data from the query. Since PHP does copy by reference, $result = $stmt; doesn't copy the data, it just references the same closed statement.
The fetch syntax also isn't quite what you had: you need to bind some placeholder variables with eg $stmt->bind_result($name, $description); and then call $stmt->fetch() instead of fetch_assoc.
I'm not clear exactly what login_check does but it would seem to me that you'd want to put this check earlier so that the query is not executed if the user is unauthorized.
Your original code would end up looking something like:
<?php
if (login_check($mysqli) == true) {
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0) {
echo 'No categories defined yet.';
} else {
//prepare the table
echo '<table border="1">
<tr>
<th>Category</th>
<th>Last topic</th>
</tr>';
$stmt->bind_result($name, $description);
while ($stmt->fetch()) {
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3>' . $name . '</h3>'
. $description;
echo '</td>';
echo '<td class="rightpart">';
echo 'Topic subject at 10-10';
echo '</td>';
echo '</tr>';
}
}
} else {
echo 'The categories could not be displayed, please try again later.';
}
} else {
echo <<<error
<p>
<span class="error">You are not authorized to access this page.</span> Please
login.
</p>
error;
}

Related

Data not required is being displayed

I have a form where the user enters data e.g. AXZAA QS1QS. This data is Posted to my PHP script. The PHP Script connects to a MYSQL database which contains at the moment 2 records.
The idea is that the PHP script will take the input and compare it to the records in the database. If the records exist they are displayed in a table on a web page otherwise, an error message is displayed.
I am having a number of problems with my PHP script and have modified my script a number of times. However, the thing I am having the biggest problem with is this:
When the form appears for the first time, the message record doesn't exist appears twice, this is before the user has entered any data and is seeing the form for the first time. See picture below.
After entering data (when the PHP script was partially working correctly), if there is a match i.e. records existed, along with the records in the table I would receive an error message telling me that records were not found. To see if I could resolve the problem I added code to tell me what records could not be found, the records that couldn't be found were the ones that were found and the other records from the database which I wasn't looking for. I know the SQL query in my PHP script tells the script to get everything from the database however, I would have thought the if statement would have fixed the problem.
Sorry about writing such a long problem and I hope it's not confusing.
enter code here
<?php
//Connect to the database connection file
require 'databaseconnection.php';
$searchBar=(isset($_POST['searchBar']) ? $_POST['searchBar'] :null);
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
?>
Wouldn't it be better to assign $searchbar after an if statement like
`<?php
//Connect to the database connection file
require 'databaseconnection.php';
if(isset($_POST['searchBar']))
{
$searchbar = $_POST['searchBar'];
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
}
else{
echo "<p>Please enter a search term</p>";
}
?>
You could then execute the MySQL query within that "if" statement rather than having it execute assuming there is a value

`while` is not showing the echo in php

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?

Parameterized statements and security

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?

Use cookie to get id, perform inner join on matching fields

This is my first post, but I have found this forum to be very useful! I hope you can help me.
My conundrum is this: I have users log on and then rate each other. Once a user logs in, I want them to be able to see the ratings they made (this one I got working - the reviews I can select by a unique id generated by a form) and also see a summary of the ratings that they have received. This is where it seems to get tricky. I tried an inner join but it didn't produce any results.
Right now I have this part up above my html
<?php
include "connect.php";
if(isset($_COOKIE['ID_my_site']))
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
while($info = mysql_fetch_array( $check ))
{
//if the cookie has the wrong password, they are taken to the login page
if ($pass != $info['password'])
{
header("");
}
//otherwise they are shown the admin area
else
{
echo "";
echo "";
}
}
}
else
//if the cookie does not exist, they are taken to the login screen
{
header("");
}
include "settings.php";
?>
And this part after my html
<?php
include('connect.php');
$result = mysql_query("SELECT r.user, r.rating1, r.rating2, r.rating3, u.username
FROM reviews r INNER JOIN users u ON r.user=u.username
WHERE r.user='$userid' ORDER BY r.user DESC")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr>
<th></th>
<th>View Comments</th>
<th>Rating 1</th>
<th>Rating 2</th>
<th>Rating 3</th>
</tr>";
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>View/Print</td>';
echo '<td>' . $row['rating1'] . '</td>';
echo '<td>' . $row['rating2'] . '</td>';
echo '<td>' . $row['rating3'] . '</td>';
echo "</tr>";
}
echo "</table>";
?>
Unfortunately, I don't get any results at all, though I see about 20 ratings for this person in the sql table.
It's also throwing a "Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in reviews.php on line 19" error.
There's probably a stupid mistake in there, but I'm getting codeblind and frustrated.
Thank you for any help!
if this is line 19:
while($row = mysql_fetch_array( $result )) {
echo "<tr>";
echo '<td>View/Print</td>';
echo '<td>' . $row['rating1'] . '</td>';
echo '<td>' . $row['rating2'] . '</td>';
echo '<td>' . $row['rating3'] . '</td>';
echo "</tr>";
}
you should use the position of the values inside the array like 1,2,3 .. and so on , not ratings1 ,ratings2 .. and so on.

Unable to sort with date

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.

Categories