How to dump whole MySQL contents from PHP? - php

Is there a clean way (no hardcoding) in which I can dump all the contents of a database directly to HTML using PHP?
I don't want to run queries for every table and step through the results, outputting them. I need this for testing purposes, so the tables aren't that big.
Any hints?
I want this done directly in my php file, where the rest of the test takes place, so that I may compare with the sample. I need to do this automatically, so can't really use tools like PHPMyAdmin.

Something like this ought to work:
<?php
function dump_mysql_results($mysql_table){
$query = mysql_query("SELECT * FROM `$table` WHERE 1",[your connection]) or die(mysql_error());
if (!mysql_num_rows($query)){die("No rows in $table");}
while($r=mysql_fetch_array($query)){
if (!isset($html)){
$keys = array_keys($r);
$html = "<tr>";
foreach($keys as $key){
$html .= "<th>$key</th>";
}
$html .= "</tr>";
}
$html .= "<tr>";
foreach($r as $value){
$html .= "<td>$value</td>";
}
$html .= "</tr>";
}
return "<table>".$html."</table>";
}
//ADDING a loop to dump the whole db:
$tables = mysql_list_tables ( 'database name',$link_identifier) or die(mysql_error());
while($r=mysql_fetch_array($tables)){
echo dump_mysql_results($r[0]);
}
?>

Use SHOW TABLES to get the list of tables, then iterate through them normally to select all the rows and display in HTML.
See http://dev.mysql.com/doc/refman/5.5/en/show-tables.html

What about mysqldump ?
<?php
exec('mysqldump --user=DBuser --password=DBpass --host=localhost --compact --xml DBname > file.xml');
?>
Then use simpleXML to convert xml to HTML

Related

Fetching data from database rows and populating select tag

Quick question. So what I need to do is to populate my html droplist with rows from my table. I am able to do this for one html droplist down but the moment I do this with another html droplist, it becomes a problem. you cant use mysql_fetch_array twice. any suggestions?
Below is the sample code which I referenced to do this.
query = mysql_query("YOUR QUERY HERE"); // Run your query
echo '<select name="DROP DOWN NAME">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}
echo '</select>';// Close your drop down box
Option 1:
Use below code. Please read this document
while($row = mysql_fetch_array($query)){
// Your code..
}
// add this line
mysql_data_seek($query, 0);
while($row = mysql_fetch_array($query)){
// Your code..
}
mysql_data_seek() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number.
Option 2:
You can store mysql_fetch_array($query) in one array and re-use it.
$sample_array = mysql_fetch_array($query);
while($row = $sample_array){
// Your code..
}
while($row = $sample_array){
// Your code..
}
Simple solution from my side, write a method that will take two arrays and populate Dropdown.
function populateDropDown($values,$displayArray, $nameDropdon){
echo "<select name='$nameDropdon'>"; // Open your drop down box
// Loop through the query results, outputing the options one by one
for($i=0;i<count($values);$i++)
echo '<option value="'.$values[$i].'">'.$displayArray[$i].'</option>';
echo '</select>';
}
Do not use deprecated functions, try MySQLi or PDO. If you need call the return elements from the database, just create an array to store it and use foreach many time as you need.
$query = mysql_query("YOUR QUERY HERE") or die(mysql_error());
$items = array();
while ($row = mysql_fetch_array($query)) {
$items[] = $row;
}
echo '<select name="DROP DOWN NAME">';
foreach($items as $item){
printf('<option value="%d">%s</option>', $item['id'], $item['description']);
}
echo '</select>';

php display all row data from mysql table without column name

I want to display all rows/data from a MySQL table without knowing the column names.
I have the table name but not the column names, and I want to build a grid of the data using the table HTML attribute. I was thinking of using the schema but no idea where to start, any suggestions ?
SELECT * FROM table_name;
that should give you all the data including all rows.
To get the table structure, use this SQL query:
SHOW COLUMNS FROM table_name;
From there you can then make a query that grabs all data from the table and display it as you want.
it may be helpful for you
$response = mysql_query('select * from table_name');
while($result = mysql_fetch_assoc($response))
{
foreach($result as $key => $value)
{
echo $key.'--'.$value;
}
}
This is actually an easy task to achieve with the MYSQLI_ASSOC function as it will put in the db field name as the array key. Take a look at this example:
$query = "SELECT * FROM `MyTable`";
if ($result = $mysqli->query($query)) {
echo '<table>';
foreach($result->fetch_all(MYSQLI_ASSOC) as $row) {
foreach($row as $key => $value) {
echo '<tr><td>' . $key . '</td><td>' . $value . '</td></tr>';
}
}
echo '</table>';
}
This would print all the tables key and associated values
On your select statement you could do "select * from table_name". Then, you go to your for loop() in php and can do more less like this:
$query = mysqli_query($your_connection_name, $your_sql_query);
Then, place a while loop:
<?php
while($row = mysqli_fetch_array($query)){
$item_one = $row[0];
$item_two = $row[1];
$item_three = $row[2];
? > *//end php*
your html code here (table etc)
< ? php *//start php again*
} *//end while loop*
?> *//end php*
hope it helps.

PHP Simple HTML DOM - Table row by row

I currently can parse a html table using simplehtmldom. The problem I have is that the program prints the entire table in one block.
How would I print row by row?
How could I limit the rows to just the ones with times? (see http://www.masjid-umar.org/downloads/timetable_apr.htm)
Below is the code I am currently using:
<?php
include('simple_html_dom.php');
$dom = file_get_html('http://www.masjid-umar.org/downloads/timetable_apr.htm');
$table = $dom->find('table',0);
$rows = $table->children(0)->children();
foreach($rows as $row)
foreach($row->children() as $column) {{
if(!empty($column->innertext)) {
echo $column->innertext . '<br />' . PHP_EOL;
}
}
}
The following is printed http://pastebin.com/cAMECf9f
You could store the individual cells in a multi-dimensional array and loop through that to output it, but if you just want the table, you can skip the loops and do something like:
$table = $dom->find('table',0);
echo $table->save();
Just search for the times:
foreach($dom->find('tr') as $tr){
if(!preg_match('/\d+\.\d+/', $tr->text())) continue;
echo $tr->text() . "\n";
}

why doesn't my query work

My query stop working suddently. I know it is dutch but can you detect any errors?
There are no MySQL errors. He just won't write $content to the screen.
I tried numerous things. he just stop working
<?php
$activiteiten= "SELECT
activiteiten.ActiviteitID,
activiteiten.Naam,
activiteiten.plaatsen,
agenda.TijdBegin,
agenda.TijdEind,
agenda.AgendaID,
reserveren.ReserveringTijd
FROM
activiteiten,
agenda,
reserveren
WHERE
agenda.ActiviteitID = activiteiten.ActiviteitID
AND
agenda.AgendaID = reserveren.AgendaID
";
$result = mysql_query($activiteiten) or die(mysql_error());
$content .= '<tr>';
$content .= '<td>'.$record['Naam'].'</td>';
$content .= '<td>'.$record['ReserveringTijd'].'</td>';
$content .='<td>Beschikbare plaatsen:'.$record['plaatsen'].'</td>';
$agendaID= $record['AgendaID'];
$agendaData = agendaData($agendaID);
$content.= '<td>aantal reserveringen:'.$agendaData["reserveringen"].'</td>';
$content.= '</tr>';
}
You do a mysql_query, but you never fill the $record variable. How do you expect it to have content?
Try adding:
$record = mysql_fetch_array( $result );
after the mysql_query.
You need to understand these are two different things:
mysql_query will execute a query on the server
mysql_fetch_array (and friends) will get the results in the desired format.
If you only do 1, you execute the query. That works fine, but if you are interested in the results, you need to fetch them. Sometimes you don't need to (for example, when the query is a not a select).
There are no MySQL errors. He just won't write $content to the screen.
What about adding:
echo $content;
If you don't print it, then you won't see anything :)
Apart from that, aren't you mixing $result and $record?
Your code is missing mysql_fetch_assoc call after mysql_query, it should be something like this:
$result = mysql_query($activiteiten) or die(mysql_error());
while(false != ($record = mysql_fetch_assoc($result))
{
$content .= '<tr>';
$content .= '<td>'.$record['Naam'].'</td>';
$content .= '<td>'.$record['ReserveringTijd'].'</td>';
$content .='<td>Beschikbare plaatsen:'.$record['plaatsen'].'</td>';
$agendaID= $record['AgendaID'];
$agendaData = agendaData($agendaID);
$content.= '<td>aantal reserveringen:'.$agendaData["reserveringen"].'</td>';
$content.= '</tr>';
}
Stopped working and not printing out any error rises the suspicion that the data in the database has somehow changed and the query simply does not get any rows.
Execute your query in a database environment like phpMyAdmin and check if any rows are returned.
Otherwise check the other answers for mysql-php-related errors.
$result = mysql_query($activiteiten) or die(mysql_error());
while ($record = mysql_fetch_array($result, MYSQL_ASSOC))
{
// Your $record now contains the data you want
}
You have the query result stored in $result but you do not then go on to do anything with $result - you need to do something like:
$record = mysql_fetch_assoc($qry_result);
to retrieve the record results from $result. If you expect more than one result you'll need to use a while loop to loop through all the results
Change:
$content .= '<tr>';
To:
$content = '<tr>';
And remember to echo the $content on the page.
Make sure you have error reporting on so you see immediately if the problem lies in uninitialized PHP variable or somewhere else.

Looping through Array in PHP returned from MySQL Query

I have a part of an application that loops through a return of a MySQL query (as we all know) in the form of an Array. However, I need several different format settings placed on some of the items returned, for example, one column needs Japanese currency, the other has American currency and one of the returned items is a link to an image.
I would use the names of the column, however this same function that I am using to accomplish this will be used for many different tables.
This is what I have for the loop so far.
while($row = mysql_fetch_array($result)) {
for($i=0;$i<=count($row);$i++) {
if($row[i]==$row['Yen_Price']) {// I didn't expect this to work...but this is what I would like to do.
echo "Hello";
}
echo "<td>" . $row[$i] . "</td>";
}
}
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $value) {
if ($key == 'Yen_Price') {
echo "Hello";
}
echo "<td>$value</td>";
}
}
Having said that, using the same function to process all results from all possible tables will soon be rather unmanageable. You should customized this to fit the occasion like so:
while ($row = mysql_fetch_assoc($result)) {
echo "<td>Foo: $row[foo]</td>";
echo "<td>Bar: $row[bar]</td>";
}
I'd markup these results specific to each table but if you want it to be ultimately flexible, try this smelly code
// using mysql_fetch_assoc() as we don't need the numeric indices
while($row = mysql_fetch_assoc($result)) {
foreach ($row as $col => $val) {
echo '<td>';
switch ($col) {
case 'US_Price' :
printf('$%0.2f USD', $val);
break;
case 'Yen_Price' :
printf('¥%0.2f', $val);
break;
case 'image' :
printf('<img src="%s">', htmlspecialchars($val));
break;
}
echo '</td>';
}
}
Note that this is a known antipattern and you should really think about another way to approach the problem.
Use the below code. You can modify it as you want.
$select=" WRITE YOUR SELECT QUERY HERE ";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
// YOU CAN USE HERE FOR EACH LOOP AS PER YOUR REQUIREMENTS.
Thanks
Before I became a framework fanatic I used to have a bit different approach. My db library had set of methods that returned me array of record sets. This way I keep my db interaction totally separate from how I consume the record sets. Having done this, its easy to set up a grid template which can look at array and then act accordingly. Here is some pseudo code
$recordSets = $db->returnRecordSets("select some, columns from tablename");//extra param if I need array to be associative
$recordSetsCount = count($recordSets);
if($recordSetsCount == 0){ echo 'Nothing to be done!'; //exit or return or break here}
for($i=0; $i< $recordSetsCount; $i++ == 0){
$recordSet = $recordSets[$i];
/*Inspect the $recordSet array and use it*/
}

Categories