Outputting multiple rows from database using MySQL and PHP - php

I've written some simple php code designed to retrieve data from a database based on the session id. If the session ID is 1 then I query the database to find all entries with the UserID of 1 and then output them.
This works to a certain extent, I can get the query to output the correct entries but for some reason it never outputs the most recent entry, instead it skips it and outputs the rest instead.
My code is below, can anyone spot what I'm doing wrong?
Thanks
$id = $_GET['id'];
if ($id)
{
$sql = "SELECT * FROM `forum_topics` WHERE `uid`='" . $id . "'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res) == 0)
{
echo "You haven't got any adverts to display";
}
else
{
$row = mysql_fetch_assoc($res);
echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\" width=\"100%\">\n";
echo "<tr align=\"center\"><td class=\"forum_header\">Title</td><td class=\"forum_header\">User</td><td class=\"forum_header\">Date Created</td></tr>";
while ($row2 = mysql_fetch_assoc($res))
{
echo "<tr align=\"center\"><td>" . s($row2['title']) . "</td><td>" . uid($row2['uid']) . "</td><td>" . $row2['date'] . "</td></tr>";
}
echo "</table>\n";
}
}

First things first
$id = $_GET['id'];
if ($id)
The code above has an SQL-injection bug!
Change it and all code like it everywhere to
$id = mysql_real_escape_string($_GET['id']);
if ($id)
For info on SQL-injection see: How does the SQL injection from the "Bobby Tables" XKCD comic work?
Secondly your question
I think your problem is might be transactions.
The most recent entry of your user has not been committed yet.
This means that whilst it has not been committed, only the user that posted it can see it (because the entry is in his transaction).
People in other sessions (including you) will not see that entry until after the transaction of that user is closed.

It looks to me like this line is the problem:
$row = mysql_fetch_assoc($res);
That line is fetching the first row, so your while loop starts at the second row (since you already fetched the first row, and the pointer was moved to the next row).
Try removing the line I mentioned and see if it works.

Related

Method to print MySQL row in PHP using foreach statement?

I am new to PHP and programming, but am attempting to print out the results from each row of one of my MySQL database tables.
Using a set of while loops I achieved this:
while($placeHolder = $query->fetch_assoc()){ // use assoc
echo "<div class='placeHolder'><img src=" . $placeHolder['photo']. " /></div>";
echo "<br />";
}
while($placeHolder2 = $query2->fetch_assoc()){
echo "<div class='placeHolder2'>" . $placeHolder2['name'] . "</div>";
echo "<br />";
}
//etc, etc...
Besides being inefficient, I'm assuming this may also be a security risk.
Is there a better way to do this, possibly using a foreach statement?
Here is my SQL code I forgot to include:
$query = mysqli_query($conx, $sql);
$query2 = mysqli_query($conx, $sql);
$sql = ('SELECT id,name,picture FROM table ORDER BY name DESC LIMIT 50');
I dont think using a foreach statement to print out the results would make it any less safe/unsafe. It really depends on your query. You should be able to print all of them using a foreach doing something like:
$result = $query->fetch_all(MYSQLI_ASSOC);
foreach($result as $row) {
echo $row['photo'];
}
Note** to use fetch_all you would need mysqlnd installed
edit: looking at your query nothing can be injected there. No outside variables being used in the query, so its safe. I would just use the while loop that you originally posted.
edit 2: link to fetch_all documentation: http://php.net/manual/en/mysqli-result.fetch-all.php

Print MySQL table in PHP without knowing the columns

Im currently making a private "list management" system in which I store SQL queries in the database. So that I can via the front-end create new "lists" (which basicly are sql queries), and view them.
I have made the front end so you can save queries into the database, and im at the point where I want PHP execute and print out the results of one of my queries. This happens when I select one of my stored "lists" on my frontend. So when I press one of the lists, it should execute the SQL query. So far, so good.
But how can I, via PHP, print a table (like the one you get out from phpMyAdmin when viewing the contents of a table) without knowing how many / what columns exists? I want the script to be dynamic, so I can view results of all kinds of SELECT queries (on different tables).
Any tips or pointers?
Rather than using deprecated libraries, use PDO instead.
$db = new PDO($dsn); //$dsn is the database connection strings. Depends on your DB.
//it can be as simple as "odbc:CONN_NAME"
$stmt = $db->prepare("SELECT * FROM $tablename");
//be sure to sanitize $tablename! use a whitelist filter, not escapes!
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); //fetch as associative array
if($rows){
//check if there are actual rows!
$first_row = reset($rows); //Resets the internal pointer, return the first elem.
$header_str = '<th>' . implode('</th><th>', array_keys($first_row)) . '</th>';
$table_body_rows = array();
foreach($rows as $row){
$table_body_rows[] = '<td>' .
implode('</td><td>', $row) .
'</td>';
}
$body_str = '<tr>' . implode('</tr><tr>', $table_body_rows) . '</tr>';
$tbl = "<table><thead><tr>$header_str</tr></thead><tbody>$body_str</tbody></table>";
} else {
//something went wrong
}
show tables is probably what you need
echo "<table><tr>";
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "<td> $row[0] </td>";
}
echo "</tr></table>"
mysql_free_result($result);
If you need to print a row with header (column names), you have to do it this way:
$result=mysql_query("SELECT * FROM yourtable WHERE 1");
if (mysql_num_rows($result)<1) echo "Table is empty";
else
{
$row=mysql_fetch_assoc($result);
echo "<table>";
echo "<tr>";
echo "<th>".join("</th><th>",array_keys($row))."</th>";
echo "</tr>";
while ($row)
{
echo "<tr>";
echo "<td>".join("</td><td>",$row)."</td>";
echo "</tr>";
$row=mysql_fetch_assoc($result);
}
echo "</table>";
}
This is just the basic concept. If your table has values which may contain HTML tags and other stuff, you'll need to apply htmlspecialchars() on all values of $row. This can be done with array_walk(). Furthermore you didn't mention what PHP version are you using and what MySQL API do you prefer. Some people suggested to use mysqli or PDO, that's up to you to rewrite the code according to your preferred API.

Php/mysql search whith custom Dispaly

I'm trying to make a simple search engine using php & mysql . I know how get mysql result using php. Its Work.
ex : - Mysql database stored this (database table filed "meta")
I am having some difficulty with my PHP/MySQL search. It worked great
a year ago, but for some reason it has just stopped working. I have
tried searching and cannot figure it out. I have it echo my query but
it never adds in the WHERE clause. Any help is much appreciated. Form
Code: PHP Code:
Search word is searching
I Need to dispay search result like this
I have tried searching and cannot figure it out. I have it echo my
query but it never adds in the WHERE clause. Any help is much
appreciated. Form Code: PHP Code:
$query= mysql_query("SELECT meta FROM data WHERE LIKE '%searching%' ");
$count = mysqli_num_rows($query);
if($count >0){
while($row = mysqli_fetch_array($query)) {
echo "$row[id]'>$row[name]</option>";
$count =1;
}
else{
echo "<option value='' selected='selected'></option>";
}
mysqli_close($con);
From the code above here, there's a couple of issues that stand out:
The echo for the option doesn't have an open for , so it's not going to show.
When you're echoing information from the $row variable, you're referencing id and name, but the query is only outputting meta.
The query isn't searching on a field for the where clause, and is therefore failing
The code, from what I can see, should be changed to the following to work (assuming no other surrounding issues):
$query = mysql_query("SELECT meta, id, name FROM data WHERE meta LIKE '%searching%'");
$count = mysqli_num_rows($query);
if ($count > 0)
{
while ($row = $mysqli_fetch_array($query))
{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
$count = 1; // not sure why this needs to be here, but it's in your code so I'm keeping it there
}
}
else
{
echo "<option value='' selected='selected'></option>";
}
mysqli_close($con);

Return Specific Row From DB

I have multiple links on a page where each link is suppose to return a specific row of data from a database. When the link is clicked, the user is forwarded to another page where the info associated with that link is displayed. Here is the code:
//db connection: (using xampp)
mysql_connect('localhost', 'root', '');
mysql_select_db('db_name');
$sql = "SELECT * FROM user_input";
$records = mysql_query($sql);
//code:
<div>
$open_report = mtsql_fetch_assoc($records);
echo "Error Report# {$open_report['id']};
echo "<p>" .$open_report['comments'] . "</p>";
</div>
The problem is it always returns the same row of data. Each row in the db is associated with a link and when that link is clicked I want to return the associated row of data in the db. I think it may have to do with this line: $sql = "SELECT * FROM user_input"; but I'm not sure how to fix it. If anyone can help it would be greatly appreciated.
I have restructured my answer to give it a better flow. I also noticed you are using mysql_ not mysqli_ . You need to use mysqli_ as mysql is depreciated.
EDIT: This would be the page that displays all the error reports. You would want to output them in the form of a hyperlink that passes a GET parameter to the page that shows the details.
$sql = "SELECT ID, Description, etc, etc from reports";
$open_reports = mysqli_query($sql);
//error check here as well if ANY results were returned
while($row = mysqli_fetch_array($open_reports, MYSQLI_ASSOC)) {
echo ''' . $open_reports['Description'] . '';
}
This will give you links that look like
detailspage.php?id=1 detailspage.php?id=2
etc...
On the "detailspage.php" You can capture that ID and display dynamic information on that same page.
if (isset($_GET['ID'])){
$sql = "Select * from user_input where ID='" . $_GET['id'] . "'";
$records = mysqli_query($sql)
while($open_report = mysqli_fetch_array($records, MYSQLI_ASSOC)) {
echo "Error Report# " . $open_report['id'] . "<br/>";
echo "<p>" .$open_report['comments'] . "</p>";
}
}

Resource id 5 error in sql

Result is returning a resource id 5 error not sure what for but i am new too this
The main issue is that my if statement is not working and i thought that was due to my result
$query = "select * from logindetails where online='1'";
$result = mysql_query($query);
echo $result;
if (mysql_num_rows($result) == 1) {
while ($row = mysql_fetch_array($result)) {
echo $row['online'] . $row['username'] . $row['password'] . $row['emailaddress'] . $row['familyname'] . $row['givenname'];
}
} else {
}
mysql_close();
?>
It's not really an error. The problem is echo $result; - You can't just print that. It doesn't know what you want to print. Also, I suggest using mysqli.
You're not really getting an error. What you're seeing is a numeric resource identifier for an external resource which in this case, is a resource in the database. Probably what you're looking for is mysql_num_rows() which will tell you the number of rows returned. You'll notice by following that link that the mysql* functions are deprecated and it's recommended that you use mysqli or PDO.
The above code outputs resource id 5 because you have given echo in the 3 line,which means your query is valid ,and the code is correct,Try giving echo mysql_num_rows($result)
Instead of echo $result, use echo $result->Row; The $result itself is an object. You want to access the Row attribute of that object.
Your if statement is only going to work if only one user is online, also. If there are more than one users online, then you are going to have more than one row, so your if statement breaks.
Try
foreach ($result as $row) {
echo $row['online'] . $row['username'] . $row['password'] . $row['emailaddress'] . $row['familyname'] . $row['givenname']. "\n";
}

Categories