Method to print MySQL row in PHP using foreach statement? - php

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

Related

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.

New row when displaying every new echo $row ['username']

I want if is possible to display the username in a new row instead of one next to the other.
e.g.:
admin
user1
user2
admin
user1
user2
Here is my code:
$con = mysql_connect('localhost','root','');
mysql_select_db('chatbox',$con);
$sql = "SELECT `username`
FROM `users`
ORDER BY `username` ASC";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_array($result))
{
echo $row['username']; //over here
}
?>
Use either
echo $row['username'] . "<br>" . "\n";
or
echo $row['username'] . "<br>" . PHP_EOL;
which will produce both clean HTML and new lines on screen for each word/name.
Sidenote: It's important to use double quotes for the \n. If not and using single quotes such as '\n' will echo n which is not what you want. Therefore, use "\n".
Nota: \n and PHP_EOL will only produce new lines/carriage returns in HTML source and not on screen, which I believe is what the ultimate goal is.
Plus, if used when writing files, will place them on seperate lines.
Therefore, you need to add <br> for your purpose.
Footnotes:
mysql_* functions are deprecated and will be removed from future PHP releases.
Use mysqli with prepared statements, or PDO with prepared statements,
they're much safer.
You should use the following as your while loop:
while($row = mysql_fetch_array($result))
{
echo $row['username'], "<br/>", PHP_EOL;//over here
}
PHP_EOL specifies a platform independent new line character.
Note: mysql function is deprecated since PHP 5.5, so you have to move to mysqli function.
If you want to use foreach approachment, then it should be like this:
<?php
$row = mysql_fetch_array($result);
foreach($row as $key => $value) echo $row['username'].PHP_EOL;

simple MySQL query via PHP

I have a table with about 500,000 rows, and need to query it to retrieve results. Basically the user just inputs a case number, and then I want to execute the following query and display the results using a while loop
if (!empty($_POST["casenum"])) {
$result2 = mysql_query("SELECT Box_Content.case_number, Transfer.number, Transfer.location, Box.number FROM Box_Content, Transfer, Box WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id and Box_Content.case_number = '".$_POST['casenum']."'");
while ($row = mysql_fetch_array($result2)) {
echo "Case number: ".$casenum." text ";
echo "<br />";
}
} else {
echo "<h4>WARNING!!! Search criteria entered not valid. Please search again.</h4>";
}
What am I doing wrong here?
EDIT:
It works now if only one row is returned, but for two rows, it seems to be trying to print the entire table...
$casenum = $_POST["casenum"];
echo "<br />The case number entered is: $casenum<br />";
if (!empty($_POST["casenum"]))
{
$result2 = mysql_query("SELECT Box_Content.case_number, Transfer.number as transfer_number, Transfer.location as transfer_location, Box.number as box_number FROM Box_Content, Transfer, Box WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id and Box_Content.case_number = '" . $_POST['casenum'] . "'");
while($row = mysql_fetch_array($result2))
{
print_r ($row);
echo "<br />";
echo "<b>Case number: </b>" . $row['case_number'] ."<br />";
echo "<b>Transfer number: </b>" . $row['transfer_number'] ."<br />";
echo "<b>Transfer location: </b>" . $row['transfer_location'] ."<br />";
echo "<b>Box number: </b>" .$row['box_number'] ."<br />";
}
}
else
{
echo "<h4>WARNING!!! Search criteria entered not valid. Please search again.</h4>";
}
var_dump($_POST);
Try:
while ($row = mysql_fetch_array($result2)) {
echo "Case number: ". $row['Box_Content.case_number'] ." text ";
echo "<br />";
}
$row['case_number'] will output the case_number retrieved for each row in your resultset.
However, you should look into doing one of two things:
Start using best practices.
Start using a non-deprecated SQL library (mysqli, PDO).
This query is susceptible to SQL injection:
"SELECT Box_Content.case_number, Transfer.number, Transfer.location, Box.number
FROM Box_Content, Transfer, Box
WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id
and Box_Content.case_number = '".$_POST['casenum']."'"
Use mysql_real_escape_string($_POST['casenum']) to patch this.
Reference: http://php.net/manual/en/function.mysql-real-escape-string.php
The mysql_* functions have long been deprecated due to unprepared statement operations. Look into either mysqli or PDO for your project instead.
What am I doing wrong here?
1) $casenum isn't set in your code... (Please tell me it is nothing and you don't have register superglobals turned on?!) You would probably want $row['case_number']
2) But anyway, that's not really what you are doing wrong... Your biggest mistake is using user input without any kind of validation or sanitization...
Imagine if $_POST["casenum"] was equal to...
' or 1=2 union select user,password,email,salt from users
You seem to be using $casenum from nowhere.
Try:
while($row = mysql_fetch_assoc($result2))
echo "Case number: ".$row['number']." text <br />";
When using the mysql_fetch functions assoc will bring back named indexed data, num will bring back numberic indexed data and array will bring back both, so try to use one or the other.
Then when you do $row = mysql_fetch_assoc($result2) your essentially saying for each row of data returned store it as a (in this case associative) array in $row, so you can then access your data via the standard array commands ($row['foo']).

mysql_fetch_array with while loop to echo list of URLs

I have a list of urls that I need to echo from my "menu" table. Here is what I have so far, but I can't seem to figure out the rest of it. The urls below are obviously there to show the format of the original HTML.
<?php
$results = mysql_query("SELECT * FROM menu WHERE level='$level'");
$row = mysql_fetch_array($results);
?>
<li>Achievments</li>
<li>Avatar</li>
.... more urls ....
You need to do it in a loop, usually a while loop:
<?php
$results = mysql_query("SELECT * FROM menu WHERE level='$level'");
while ($row = mysql_fetch_array($results)) {
echo'<li>'.$row['name'].'</li>';
}
?>
I've improvised on your column names (uri and name), they will probably be something different.
Close. Personally I would use put it into a while loop to read all the values. then echo them one by one.
while($row = mysql_fetch_array($results)){
echo "<a href = \"". $row['fieldtouse'] . "\" />". $row['textforlink'] . "<a/>";
}
That is the idea. Loop through results. echo results.
I believe this is a simple case of iterating over the result list. And as you already mentioned you should not use a single mysql_fetch_array, but in a loop like this:
while ($row = mysql_fetch_array($results)) {
print "<li><a href='.../$row[0]' target='evil'>$row[1]</a></li>";
}
Now $row[0] and $row[1] will have to be adapted. Prefer mysql_fetch_assoc to get named result columns, and then apply e.g. $row[url] and $row[title] instead of the numeric keys.

Outputting multiple rows from database using MySQL and 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.

Categories