I'm pulling data from a database but only getting the first row into the dynamically produced html table.
I've tried adding another foreach loop but that isn't the answer… I'm out of ideas...
$conn = new PDO('mysql:host=localhost;dbname=jeuxvideo', $dbUserName, $dbPassword);
$sql = "SELECT * FROM jeuxvideo";
$result = $conn->prepare($sql);
$request = $result->execute();
echo "<table border='1'>";
echo "<tr><td>Id</td><td>Titre</td><td>Prix<td>Date de Sortie</td><td>Genre</td><td>Origine</td><td>Mode</td><td>Connexion</td></tr>\n";
$row = $result->fetch(PDO::FETCH_ASSOC);
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
echo "</table>";
This code pulls all the correct info and puts it in the right place in the html table, but for some Reason it doesn't collect the Following rows data...
This line only fetches one row:
$row = $result->fetch(PDO::FETCH_ASSOC);
You need to fetch as many rows it can give you. Once there are no more rows to fetch the function will return FALSE, so you can use with the while loop, like this:
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
echo "</table>";
Since you don't have any variables you need prepared for your query, you can simply do:
<?php
$stmt = $pdo->query('SELECT * FROM jeuxvideo');
echo '<table>';
foreach ($stmt as $row) {
echo '<tr>';
echo "<td>$row['name']</td>";
echo "<td>$row['url']</td>";
echo "<td>$row['timestamp']</td>";
echo '</tr>';
}
echo '</table>';
A 2nd method would be:
<?php
$stmt = $pdo->query('SELECT * FROM jeuxvideo');
echo '<table>';
while ($row = $stmt->fetch()) {
echo '<tr>';
echo "<td>$row['name']</td>";
echo "<td>$row['url']</td>";
echo "<td>$row['timestamp']</td>";
echo '</tr>';
}
echo '</table>';
Try this
$conn = new PDO('mysql:host=localhost;dbname=jeuxvideo', $dbUserName, $dbPassword);
$sql = "SELECT * FROM jeuxvideo";
$result = $conn->prepare($sql);
$request = $result->execute();
echo "<table border='1'>";
echo "<tr><td>Id</td><td>Titre</td><td>Prix<td>Date de Sortie</td><td>Genre</td><td>Origine</td><td>Mode</td><td>Connexion</td></tr>\n";
$row = $request->fetch_all();
echo "<tr>";
foreach ($row as $key => $value) {
echo "<td>$value</td>";
}
echo "</tr>";
echo "</table>";
Related
Ok so I'm trying to make a localhost site that has the same base functions as Phpmyadmin, and everything is working other than displaying a table's data.
here's an example of what I'm trying to accomplish:
though I'm not sure how to accomplish this. Here is some code to show you what I have now
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$columquery = "SHOW COLUMNS FROM " . $table;
$columresult = mysql_query($columquery);
while ($row3 = mysql_fetch_array($columresult)) {
echo "<th>" . $row3['Field'] . "</th>";
}
?>
<?php
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($result2)) {
foreach($row2 as $var) {
echo "<tr><td>" . $var . "</td></tr>";
}
}
?>
</table>
</div>
Yes yes, I know it's horrible.
The other answers use the mysqli API while you're using the older, no longer supported mysql API. I really recommend upgrading to either mysqli or PDO, but if you want to stay with mysql you can use the following solution:
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$shouldOutputHeaders = true;
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2)) {
if ($shouldOutputHeaders) {
echo "<tr>";
foreach (array_keys($row2) as $header) {
echo "<th>" . $header . "</th>";
}
echo "</tr>";
$shouldOutputHeaders = false;
}
echo "<tr>";
foreach ($row2 as $var) {
echo "<td>" . $var . "</td>";
}
echo "</tr>";
}
?>
</table>
</div>
If i understood you well, You need mysqli_fetch_row.
$q= "SELECT * FROM table";
$result = $mysqli->query($q)
while ($row = $result->fetch_row()) {
print ("$row[0], $row[1]);
}
I think you are looking for something very ugly like the following. I found it in the garbage. I am not responsable for any use of it:
<?php
$db=Db::getConnection(); // singleton
$this->var['result']=$db->query($_POST['query']);
if (isset($this->var['result'])) {
echo '<table cellpadding="5" cellspacing="2" border="1"><tbody>';
$titles=array_keys(#$this->var['result'][0]);
echo '<tr>';
foreach($titles as $title)
echo '<th>'.$title.'</th>';
echo '</tr>';
foreach($this->var['result'] as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
}
?>
Db is an standard singleton that contains a mysqli private object.
query() contains something like
$sql = $this->mysqli->query($query);
$this->lastInsertId = $this->mysqli->insert_id;
$errno = $this->mysqli->connect_errno;
if ($errno === 0) {
if ($this->mysqli->field_count > 0) {
while ($row = $sql->fetch_assoc()) $response[] = $row;
return $response;
}else{
return true;
}
}
to create the "array of arrays" response. Suitable for the output you are looking for.
I've added some escaping and only queried the database when needed:
// Print table tags
echo "<table>";
// Print out records
$q = mysql_query("SELECT * FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print out columns
$columns = array_keys($res[0]);
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$columns).'</th></tr>';
// Print out table data
echo'<tr><td>'.implode('</td><td>', array_map('htmlspecialchars',$res).'</td></tr>';
} else {
// IFF there is no data, print out columns
$q = mysql_query("SHOW COLUMNS FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print columns
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$res).'</th></tr>';
}
}
echo '</table>';
Hope this helps,
I am trying to get the column names and data from a table using mysqli and php. Any help is appreciated.
I know how to do this in java by more or less this code:
String [] header= new String[numberOfColumns-1];
//Code to get column names in header array
String table = "<table><tr>"
for(int i=0;i<numberOfColumns-1;i++){
table= table + "<td>" + header[i] + </td>;
}
table = table + </tr>;
while(result.next()!=null){
table = table + <tr>
for (int j = 0 ; j < numberOfColumns-1 ; j++){
table = table + <td> + result.getString[j] + </td>
}
table = table + </tr>
}
But i have no idea how to do it in php. Each table is different but what i have to far for the one table:
include("config.php");
session_start();
$sql = ($_POST['q']);
$result = mysqli_query($db,$sql);
echo "<tr>";
echo "<td>First Name</td>";
echo "<td>Last Name</td>";
echo "<td>Date of Birth</td>";
echo "<td>Contact Details</td>";
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
echo "<td>" . $rowitem['fname'] . "</td>";
echo "<td>" . $rowitem['lname'] . "</td>";
echo "<td>" . $rowitem['dob'] . "</td>";
echo "<td>" . $rowitem['contact'] . "</td>";*/
echo "</tr>";
}
echo "</table>"; //end table tag
EDIT: Is the implementation of the fetch_fields correct?
include("config.php");
session_start();
$sql = ($_POST['q']);
$result = mysqli_query($db,$sql);
$finfo = mysqli_fetch_fields($result);
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>" . $val->name . "</td>"
}
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
for($x =0; $x < count($finfo);$x++){
echo "<td>" . $rowitem[$x] . "/td";
}
echo "</tr>";
}
echo "</table>";
EDIT 2: Database Connection.php
<<?php
include("config.php");
session_start();
$sql = ($_GET['q']);
$result = mysqli_query($db,$sql);
echo "<table border='1' class='table_info'>";
$finfo = mysqli_fetch_fields($result);
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>" . $val->name . "</td>";
}
echo "</tr>";
while($rowitem = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo "<tr>";
foreach ($row as $value) { (line 18)
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>"; //end table tag
?>
Error:
Notice: Undefined variable: row in databaseConnection.php on line 18
Warning: Invalid argument supplied for foreach() in databaseConnection.php on line 18
You can call mysqli_fetch_fields on the $result object, and retrieve the name property for each object in the returned array. See documentation for examples.
There are a couple ways to do this:
Use array_keys() to grab the names of the keys from an associative array:
$rowitem = mysqli_fetch_array($result, MYSQLI_ASSOC);
$header = array_keys($rowitem);
Use mysqli_fetch_fields() to grab the field objects, and parse out the names into an array using array_map():
// Helper function to use in array_map
// (For PHP < 5.3. If >= 5.3.0, use the second version)
function getFieldName($field) { return $field->name; }
// For PHP < 5.3:
$header = array_map("getFieldName", mysqli_fetch_fields($result));
// For PHP >= 5.3.0:
$header = array_map(function($o) { return $o->name; }, mysqli_fetch_fields($result));
As mentioned you can use $result->fetch_fields() to get the field information from the result and this includes the name of each field.
For what you're trying to acheive this code should work for pretty much any table/query:
<?php
/* Connect to mysql */
$mysqli = new mysqli("localhost", "username", "password", "database");
/* Check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Your query */
$query = "SELECT * from table";
if ($result = $mysqli->query($query)) {
/* Output HTML table */
echo "<table border='1'>";
/* Get field information for all returned columns */
$finfo = $result->fetch_fields();
/* Output each column name in first table row */
echo "<tr>";
foreach ($finfo as $val) {
echo "<td>".$val->name."</td>";
}
echo "</tr>";
/* Fetch the result and output each row into a table row */
while($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
$result->free();
echo "</table>";
}
$mysqli->close();
(Obviously you should never query a database from a $_POST variable without some serious sanitisation of the input, but I'll assume that was just for your convenience.)
You can Echo in a table..
$result = mysqli_query($db,$sql)
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysqli_num_fields($result);
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysqli_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysqli_fetch_row($result))
{
echo "<tr>";
// $row is array... foreach( .. ) puts every element
// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysqli_free_result($result);`
I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>
I want every different record of database to be display on each table rows, but I'm unable to retrieve different record for each row and column. Please give me suggestion where I can paste than while block so it will give different result for each row and column.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$rec_limit = 10;
$scriptname=$_SERVER['PHP_SELF'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('online_shopping'); // include your code to connect to DB.
$tbl_name="mobile_db"; //your table name
$start = 0;
$limit = 5;
$sql = "SELECT id,company,model,price,availability,image FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$company=$row['company'];
$model=$row['model'];
$available=$row['availability'];
$price=$row['price'];
}
echo "<table border='2'>";
$j = 0;
for($j = 0; $j<5; $j++)
{
echo "<tr>";
for($i = 0; $i<3; $i++)
{
echo "<td>";
echo "<table border='2'>";
echo "<tr>";
echo "<td><img src='abc.jpg' height='250' width='250'/></td>";
echo "</tr>";
echo "<tr>";
echo "<td>";
echo "<table border='2'>";
echo "<tr>";
echo "<td><b>Brand : </b></td>";
echo '<td>'.$company.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Model : </b></td>";
echo '<td>'.$model.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Availability : </b></td>";
echo '<td>'.$available.'</td>';
echo "</tr>";
echo "<tr>";
echo "<td><b>Price : </b></td>";
echo '<td>'.$price.'</td>';
echo "</tr>";
echo "</table>";
echo "</td>";
echo "</tr>";
echo "</table>";
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
You need to move the table rows inside the fetch loop or store the row in an array. I have simplified your tables to make the example clearer:
$result = mysql_query($sql);
if (!$result) {
/* Error */
}
echo '<table>';
while ($row = mysql_fetch_array($result)) {
echo '<tr><td><img src="', htmlspecialchars ($row['image']), '">';
echo '<tr><td><table>';
echo ' <tr><th>Brand<td>', htmlspecialchars ($row['company']);
echo ' <tr><th>Model<td>', htmlspecialchars ($row['model']);
echo ' <tr><th>Availability<td>', htmlspecialchars ($row['availability']);
echo ' <tr><th>Price<td>', htmlspecialchars ($row['price']);
echo ' </table>';
}
echo "</table>\n";
Some notes about the code:
Test the return value of mysql_query(). The query might fail.
Escape your output using htmlspecialchars().
You should use <th> elements for your headings and style those, instead of using inline <b> elements.
I added output of $row['image'] which might not do what you want.
And do not use the deprecated mysql extension. Use PDO or mysqli instead.
In your while loop you always rewrite the same variables, after loop you have only last record saved.
In the loop, you have to save records into array.
In your code you have nested tables, but in the first one, there is only one row and one table cell which contains another table. I use just nested table.
<?php
...
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_array($result)) {
$data[] = $row;
}
if (count($data) > 0) {
echo '<table>';
foreach ($data as $row) {
echo '<tr>';
echo '<td>Brand: ' . $row['company'];
echo '<td>Model: ' . $row['model'];
echo '<td>Availability: ' . $row['availability'];
echo '<td>Price: ' . $row['price'];
}
echo '</table>';
} else {
echo 'no records';
}
?>
Not sure I fully understand what you are trying to accomplish but try this.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$rec_limit = 10;
$scriptname=$_SERVER['PHP_SELF'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('online_shopping'); // include your code to connect to DB.
$tbl_name="mobile_db"; //your table name
$start = 0;
$limit = 5;
$sql = "SELECT id,company,model,price,availability,image FROM $tbl_name LIMIT $start, $limit";
$result = mysql_query($sql);
echo "<table border='2'>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['company']."</td>";
echo "<td>".$row['model']."</td>";
echo "<td>".$row['availability']."</td>";
echo "<td>".$row['price']."</td>";
echo "</tr>";
}
echo "</table>";
?>
Here's the code:
<?php
if(isset($_POST['results']) && $_POST['results'] != -1) {
$db = new PDO('mysql:host=localhost;dbname=;charset=utf8', '', '');
echo "<table border='1'>
<tr>
<th>Courses</th>
</tr>";
$stmt = $db->prepare("SELECT title FROM course WHERE `subject_id`=?");
$stmt->execute(array($_POST['results']));
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td>", $row['title'], "</td>";
echo "</tr>";
}
} else {
echo "No results found";
} echo "</table>";
}
?>
This is just returning one result into the table, when there are more results to show.
Where am I going wrong?
remove the if, because it's change the pointer of array(fetch)
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { // get the first record, remove this if
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {// get the second record and reset $row
you can change to:
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$total_rows = $stmt->rowCount();
if($total_rows > 0){
foreach($row as $item){
echo '<td>'. $item['title'] .'</td>';
}
}else{
echo 'no results';
}