I'm attempting to create a dynamic table with MYSQL's function: while(mysql_fetch_assoc).. However, when it fetches more than one result, it doesn't create the table anymore (or fill in the tags. Excuse me for explaining this incorrectly)
This is my code. Ignore the Dutch words :)
$sql2 = mysql_query("SELECT * FROM kostendb WHERE ProjectID = '$_GET[id]'") or die (mysql_error());
echo '
<table border="1" style="width:60%">
<tr>
<th>Kostencode</th>
<th>Datum</th>
<th>Bedrag</th>
</tr>';
while($res = mysql_fetch_assoc($sql2))
{
echo '<tr>';
echo '<td>' .$res['KostenID']. '</td>';
echo '<td>' .$res['Datum']. '</td>';
echo '<td>' .$res['Bedrag']. '</td>';
echo '</tr>';
}
echo '</table>';
When it finds more than one result, the while-loop doesn't do anything. When it finds just one result, it works fine.
What is causing this, and how can I fix this?
I've checked out an example script, but it's exactly using my method.
Thanks
You might have mixed mysql with mysqli.
Choose one, don't mix and this might fix your problem.
make a variable like $project = $_GET['ID'];
then put in sql statement as ....WHERE Project_ID = $project");
Try this
Related
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.
I'm actually trying to use JOINS for the first time and I'm having a tough time getting it to go. I have two tables...stories and wp_users and I'm trying to return all stories and include the display_name of the user from users along with each story.
This code works fine to get all results from stories and show story name and genre:
$results = $wpdb->get_results("SELECT * FROM stories where stories.active = 1");
foreach ($results as $row) {
echo '<tr>';
echo '<td>' . $row->story_name; '</td>';
echo '<td>' . $row->genre; '</td>';
Now I want to also include the name of the user who wrote the story ("display_name" from wp_users table)
After reading many sites about joins the below approach seemed best, but sadly it returns no results:
<?php
global $wpdb;
$sql = "SELECT stories.story_name, stories.genre, wp_users.display_name as display FROM
stories LEFT JOIN wp_users ON stories.ID=wp_users.ID where stories.active = 1";
$results = $wpdb->query($sql);
if($results->num_rows) {
while($row = $results->fetch_object()) {
echo "{$row->story_name} {$row->genre} {$row->display}<br>";
}
}
else {
echo 'No results';
}
Here are some suggestions that might help:
In your first code snippet, you are using $wpdb->get_results() while in your second snippet there is $wpdb->query(). There might be some difference in the returned value and the meaning of the parameters.
Find out about the method that asks for error messages after querying and use it to dump the message. Often if no rows are returned it is because there was an error.
Make sure num_rows really is got from $results. Here (http://codex.wordpress.org/Function_Reference/wpdb_Class) it says the expression is $wpdb->num_rows. (You'll find it by searching the site for 'num_rows', it'll scroll down.)
Try to use the MySQL Command Shell or some PhpMyAdmin sandbox to check the query. Entering the SQL directly will show typos and other problems like "unknown column" in the SQL code, and it allows to edit fast. Joining syntax varies between databases, yet your LEFT JOIN is ok to MySQL. There seems to by no problem on the syntactic level.
This docu http://codex.wordpress.org/Function_Reference/wpdb_Class may help to come clear with the code.
Got it!
<?php
global $wpdb;
$results = $wpdb->get_results("SELECT stories.story_name, stories.genre,
wp_users.display_name FROM stories LEFT JOIN wp_users ON stories.ID=wp_users.ID where
stories.active = 1");
if ($results) {
echo '<table>';
echo '<tr>';
echo '<td><b>Story Name</b></td>';
echo '<td><b>Genre</b></td>';
echo '<td><b>Last User on this Website to See</b></td>';
echo '</tr>';
foreach ($results as $row) {
echo '<tr>';
echo '<td>' . $row->story_name; '</td>';
echo '<td>' . $row->genre; '</td>';
echo '<td>' . $row->display_name; '</td>';
echo '</tr>';
}
echo '</table>';
}
?>
I'm trying to pull information and display it in a table form on a php page i have a mysql DB i have something like below which list everything in the table but i would like to have it only show certain information if a certain data is present
Columns i would like to display on the page
object_id, Name and, wish.
but i only want rows from the DB to be displayed if a column
wishState is ("pending")
this is what i have scoured around to find so far wich brings everything in.
$query="SELECT * FROM MY_TABLE";
$results = mysql_query($query);
while ($row = mysql_fetch_array($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
Thanks Ryan
The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So please don't use mysql_* anymore.
//selects data where wish is pending
$query="SELECT * FROM `MY_TABLE` WHERE `wish`='pending'";
$results = mysqli_query($your_db_connection, $query) or exit(mysqli_error());
while ($row = mysqli_fetch_array($results)) {
//show only object_id, name and wish
echo '<tr>';
echo '<td>' . $row['object_id'] . '</td>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['wish']. '</td>';
echo '</tr>';
}
$query="SELECT * FROM MY_TABLE WHERE `wish`='pending'";
That should work based on the information you gave us. WHERE tells the database to search for rows WHERE the column WISH is equal to "pending".
I have a problem reading out multiple rows that get returned from an SQLite 3 database.
I tested my querys before and i know what the result should be. But i cant seem to figure out how to read these different lines/rows that get returned from this query on a PHP based webpage.
I searched the web, including stackoverflew but i can't seem to find an anwser to this question :/
Any help would be great!
Regards
P.S. this is how i fetch my the multiple rows on my php page:
$ID[$i] = $dbase->querySingle("SELECT rowid FROM rules WHERE parameter".$i." = '$Model'");
I have this in PHP:
$query = $db->query("SELECT * FROM files WHERE OBJECT = '".$id."'") ;
// begin table
echo '<table bgcolor="#FFFFFF">'."\n";
// give titles
echo '<tr>';
echo '<td bgcolor="#669999"><b><u>File</u></b></td>';
echo '<td bgcolor="#669999"><b><u>Night</u></b></td>';
echo '<td bgcolor="#669999"><b><u>Name</u></b></td>';
echo '<td bgcolor="#669999"><b><u>comment</u></b></td>';
echo '</tr>'."\n";
//
while($row = $query->fetchArray()) {
echo '<tr>';
echo '<td bgcolor="#CCCCCC">'.$row["uniquenumber"].'</td>';
echo '<td bgcolor="#CCCCCC">'.$row["NIGHT"].'</td>';
echo '<td bgcolor="#CCCCCC">'.$row["NAME"].'</td>';
echo '<td bgcolor="#CCCCCC">'.$row["COMMENTS"].'</td>';
echo '</tr>'."\n";
}
It works here.
Hope it can help you !
i am facing a hight load in my server ichecked all my code and all of it is OK but what i am not sure about it is the ( multiple columns ) code.
i use this one
$getpics = mysql_query("select id,image_thumb from pics order by id desc limit 0,10");
while ($result = mysql_fetch_assoc($getpics)) {
$data1[] = $result;
}
$data1 = array_chunk($data1, 5);
echo '<table width="100%" border="0" cellpadding="5">';
foreach ($data1 as $row1) {
echo '<tr>';
foreach ($row1 as $column1) {
echo '
<td align="center">
<div class="imagepic">
'.$column1[image_thumb].'
</div>
</td>
';
}
echo '</tr>';
}
echo '</table>';
mysql_free_result($getpics);
so now i am confuced is that code make load in my site.
regards
Instead of writing out each line, you could buffer the output.
$buf = "<table width="100%" border="0" cellpadding="5">";
foreach ($data1 as $row1) {
$buf .= "<tr>";
foreach ($row1 as $column1) {
$buf .= "<td align='center'>";
$buf .= "<div class='imagepic'>";
$buf .= $column1[image_thumb];
$buf .= "</div></td>";
}
$buf .= "</tr>";
}
$buf .= "</table>";
echo $buf;
The nested for loop probably doesn't help either. Directly accessing the columns by name or index is probably going to be faster.
I took the liberty of making some of the more modifications. I removed one of the loops, got rid of array_chunk, and some others. I didn't really see too much wrong with it, so the problem may very well be in something else, but let me know.
$getpics = mysql_query("select id,image_thumb from pics order by id desc limit 0,10");
$out = '<table width="100%" border="0" cellpadding="5">'; // Use a string and concat
$i = 0;
while ($row = mysql_fetch_assoc($getpics)) { // No need to loop twice. Once is fine,
if(!($i%5))$out .= '<tr>';
$out .= '<td align="center">
<div class="imagepic">
'.$row['id']. /*Do you REALLY want ID? That's what foreach will give you*/ '
</div>
</td>
<td align="center">
<div class="imagepic">
'.$row['image_thumb'].'
</div>
</td>';
$i++;
if(!($i%5))$out .= '</tr>'; // Inner loop removed. You're only selecting two columns!
}
if(($i%5))$out .= '</tr>'; // close the last row.
echo $out.'</table>';
mysql_free_result($getpics);
Obviously check for bugs before using.
You can buffer the output, but the PHP script is not the blocker here. The MySQL probably shouldn't be either, since you have a LIMIT set.
Can you run DESCRIBE SELECT on that query and report the load times? Do other pages load poorly on your host as well?
the php itself is not going to cause any load issues, unless there is something huge going on outside of the code you've shown here.
usually your query is the bottleneck, try running explain on your query eg. EXPLAIN SELECT ... in a tool like phpmyadmin or via the mysql command line, then post the output here.
your query is really simple though, and since you are ordering on id (primary key, auto increment I'm assuming) the issue is not likely mysql indexing.
IF the query is causing the issue, either check your indexes (could create an index on id,image_thumb) see http://dev.mysql.com/doc/refman/5.5/en/multiple-column-indexes.html , or use memcached as a temporary caching engine for your result set.