`while` is not showing the echo in php - 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?

Related

ID is not numeric and can't be edited

So these are my codes. The id in my case is a varchar(consists of number, symbol and char). When I entered a numeric ID, I can edit the information. But when the id entered is not fully numeric, the system says " Unknown column '618XRWCG' in 'where clause'"
this is updateforecast.php
<?php
}
// connect to the database
include('connect.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (is_numeric($_POST['id']))
{
// get form data, making sure it is valid
$id = $_POST['id'];
$min = mysql_real_escape_string(htmlspecialchars($_POST['min']));
$max = mysql_real_escape_string(htmlspecialchars($_POST['max']));
$sapuk = mysql_real_escape_string(htmlspecialchars($_POST['sapuk']));
$sapus = mysql_real_escape_string(htmlspecialchars($_POST['sapus']));
$sapasia = mysql_real_escape_string(htmlspecialchars($_POST['sapasia']));
$sapmex = mysql_real_escape_string(htmlspecialchars($_POST['sapmex']));
$penuk = mysql_real_escape_string(htmlspecialchars($_POST['penuk']));
$penus = mysql_real_escape_string(htmlspecialchars($_POST['penus']));
$penasia = mysql_real_escape_string(htmlspecialchars($_POST['penasia']));
$penmex = mysql_real_escape_string(htmlspecialchars($_POST['penmex']));
// check that firstname/lastname fields are both filled in
if ($min == '' || $max == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $min, $max, $sapuk, $sapus, $sapasia, $sapmex, $penuk, $penus, $penasia, $penmex, $error);
}
else
{
// save the data to the database
mysql_query("UPDATE forecast SET Min='$min', Max='$max', sapUK='$sapuk', sapUS='$sapus', sapAsia='$sapasia', sapMex='$sapmex', penUK='$penuk', penUS='$penus', penAsia='$penasia', penMex='$penmex' WHERE Partnumber='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: viewforecast.php");
}
}
else
{
// if the 'id' isn't valid, display an error
echo 'Error!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id'])&& $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM forecast WHERE Partnumber=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$min = $row['Min'];
$max = $row['Max'];
$sapuk = $row['sapUk'];
$sapus = $row['sapUS'];
$sapasia = $row['sapAsia'];
$sapmex = $row['sapMex'];
$penuk = $row['pendingUK'];
$penus = $row['pendingUS'];
$penasia = $row['pendingAsia'];
$penmex = $row['pendingMex'];
// show form
renderForm($id, $min, $max, $sapuk, $sapus, $sapasia, $sapmex, $penuk, $penus, $penasia, $penmex, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
This is viewforecast.php
<?php
include('connect.php');
$result = mysql_query("SELECT * FROM forecast")
or die(mysql_error());
echo "<table border='1' id = 'frmnew' cellpadding='10'>";
echo "<tr>
<th rowspan='2'><center><b>Part Number</b></center></th>
<th rowspan='2'><center><b>Minimum Quantity</b></center></th>
<th rowspan='2'><center><b>Maximum Quantity</b></center></th>
<th colspan='4' scope='colgroup'><center>SHIP AGAINST PO</center></th>
<th colspan='4' scope='colgroup'><center>FORECAST FROM VARIOUS REGIONS PENDING FOR INTERCO PO</center></th>
</tr>
<tr>
<th scope='col'><center>UK</center></th>
<th scope='col'><center>US</center></th>
<th scope='col'><center>ASIA</center></th>
<th scope='col'><center>MEXICO</center></th>
<th scope='col'><center>UK</center></th>
<th scope='col'><center>US</center></th>
<th scope='col'><center>ASIA</center></th>
<th scope='col'><center>MEXICO</center></th>
</tr>";
// loop through results of database query, displaying them in the table
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['Partnumber'] . '</td>';
echo '<td>' . $row['Min'] . '</td>';
echo '<td>' . $row['Max'] . '</td>';
echo '<td>' . $row['sapUK'] . '</td>';
echo '<td>' . $row['sapUS'] . '</td>';
echo '<td>' . $row['sapAsia'] . '</td>';
echo '<td>' . $row['sapMex'] . '</td>';
echo '<td>' . $row['pendingUK'] . '</td>';
echo '<td>' . $row['pendingUS'] . '</td>';
echo '<td>' . $row['pendingAsia'] . '</td>';
echo '<td>' . $row['pendingMex'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
// close table>
echo "</table>";
?>
<p>Add a new record</p>
</body>
</html>
The previous error i stated was when i entered an id with no symbol. When i enter an id with symbols, the symbol and the character after it is hidden or something.
Please help
Your code is vulnerable to SQL Injection. You should use PDO like suggested by #IncredibleHat
Edit your updateforecast.php code select query you passed id without string change this .
$result = mysql_query("SELECT * FROM forecast WHERE Partnumber='$id'")

How to check there is data, then show nothing

I want to check if the data is empty. Is it's empty don't show enything even not the google link. If there is data then show the google link. How can I fix it?
$result = $mysqli->query("SELECT * FROM teams WHERE teamid = ".$_GET['teamid']." ORDER BY `teamname` DESC");
$teamdetails = mysqli_fetch_assoc($result);
echo '<table id=kalender_table><tr><td><h3>'.$teamdetails['teamname'].'</h3> <br>';
echo ''.$teamdetails['teamid'].'<br>';
echo ''.$teamdetails['website'].' <br></td>';
echo '<td><img src=../../logo/'.$teamdetails['image'].'></td></tr>';
echo '<tr><td colspan="2">'.$teamdetails['cmp1_name'].'</td></tr>';
echo '<tr><td colspan="2">'.$teamdetails['cmp1_adress'].'</td></tr>';
echo '<tr><td colspan="2">'.$teamdetails['cmp1_zip'].' '.$teamdetails['cmp1_city'].'</td></tr>';
echo '<tr><td colspan="2">'.$teamdetails['cmp1_phone'].'</td></tr>';
echo '<tr><td colspan="2">Google maps</td></tr>';
You can try this:
<?php
if (is_array($teamdetails) && count($teamdetails) > 0) {
// Do something
}
Simple do it with row counts, if greater then 0 show if not, nothing to show
$result = $mysqli->query("SELECT * FROM teams WHERE teamid = ".$_GET['teamid']." ORDER BY `teamname` DESC");
$teamdetails = mysqli_fetch_assoc($result);
if((mysqli_num_rows($result) > 0) {
echo '<table id=kalender_table><tr><td><h3>'.$teamdetails['teamname'].'</h3> <br>';
echo ''.$teamdetails['teamid'].'<br>';
echo ''.$teamdetails['website'].' <br></td>';
echo '<td><img src=../../logo/'.$teamdetails['image'].'></td></tr>';
echo '<tr><td colspan="2">'.$teamdetails['cmp1_name'].'</td></tr>';
echo '<tr><td colspan="2">'.$teamdetails['cmp1_adress'].'</td></tr>';
echo '<tr><td colspan="2">'.$teamdetails['cmp1_zip'].' '.$teamdetails['cmp1_city'].'</td></tr>';
echo '<tr><td colspan="2">'.$teamdetails['cmp1_phone'].'</td></tr>';
echo '<tr><td colspan="2">Google maps</td></tr>';
} else {
echo '<tr><td colspan="2">'Nothing to Show'</td></tr>';
}
right after running mysqli_fetch_assoc:
if (mysqli_affected_rows()){
...
}
you need to use "isset" function because using count() may exist rows but have no data in them.
[...]
$teamdetails = mysqli_fetch_assoc($result);
if (isset($teamdetails['teamname']) & $teamdetails['teamname']) {
echo '<table id=kalender_table><tr><td><h3>'.$teamdetails['teamname'].'</h3> <br>';
[...]
}
[...]

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.

Display result from database in two columns

EDIT: This is what I am trying to achieve: http://i.imgur.com/KE9xx.png
I am trying to display the results from my database in two columns. I'm a bit new to PHP so I haven't the slightest clue on how to do this. Can anybody help me with this? Thanks in advance.
Here is my current code:
include('connect.db.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM todo ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table width='415' cellpadding='0' cellspacing='0'>";
// set table headers
echo "<tr><td><img src='media/title_projectname.png' alt='Project Name' /></td>
<td><img src='media/title_status.png' alt='Status'/></td>
</tr>";
echo "<tr>
<td><div class='tpush'></div></td>
<td> </td>
</tr>"
while ($row = $result->fetch_object())
{
echo "<tr>";
echo "<td><a href='records.php?id=" . $row->id . "'>" . $row->item . "</a></td>";
echo "<td>" . $row->priority . "</td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
A good idea would be storing your data into a simple array and then display them in a 2-columned table like this:
$con = mysql_connect('$myhost', '$myusername', '$mypassword') or die('Error: ' . mysql_error());
mysql_select_db("mydatabase", $con);
mysql_query("SET NAMES 'utf8'", $con);
$q = "Your MySQL query goes here...";
$query = mysql_query($q) or die("Error: " . mysql_error());
$rows = array();
$i=0;
// Put results in an array
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
$i++;
}
//display results in a table of 2 columns
echo "<table>";
for ($j=0; $j<$i; $j=$j+2)
{
echo "<tr>";
echo "<td>".$row[$j]."</td><td>".$row[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
<table>
<tr>
<td>ProjectName</td>
<td>Status</td>
<td>ProjectName</td>
<td>Status</td>
</tr>
<?php
while($row = $result->fetch_object()) {
echo "<tr>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "</tr>";
}
?>
</table>
This is the thing on picture. With a bit CSS you can manipulate the tds.
Your function should look similar to this:
$query = "SELECT *
FROM todo
ORDER BY id";
$result = $mysqli->query($query);
while($row = $result -> fetch_array()) {
$feedback .= "<tr>\n<td>" . $row['item'] . "</td><td>" . $row['priority'] . "</td>\n</tr>";
}
return $feedback;
Then, in your HTML have the <table> already setup and where you would normally insert your <td> and <tr> put <?php echo $feedback?> (where $feedback is the assumed variable on the HTML page that retrieves the $feedback from the function). This isn't a complete fix, your code is hard to read, but by starting here, you should be able to continue on the path filling in all the extra information you need for the table, including your CSS.

Categories