Individually displaying stored items in an array - php

I've been having issues displaying items that i saved from my database in an array. My table has two columns for 'name' and 'details'. I successfully retrieved them using mySQLi and stored in an array but instead of displaying all the columns at once, I want to place them at different places on my webpage. eg
<p>$Name1: $Details1</p>. then on another section of the same page
<p>$Name2: $Details2</p>. This is my code:
<?php
include ("config/database.php");
$mysqli = new mysqli($host, $user, $passwd, $database);
if ($mysqli-> connect_errno){
printf("Connect failed: %s\n",$mysqli-> connect_error);
exit();
}
$query = "SELECT name, details FROM recent_properties LIMIT 3";
if($result = $mysqli->query($query)){
printf("%s: %s<br>", $row["name"], $row["details"]);
$result->free();
}
$mysqli->close();
?>

Did you try like this.Make use of loop. To display all the records.
$query = "SELECT name, details FROM recent_properties LIMIT 3";
$result = $mysqli->query($query);
if($result->num_rows()>0)
{
while($row = $result->fetch_assoc())
{
printf("%s: %s<br>", $row["name"], $row["details"]);
}
}
$mysqli->close();

$query = "SELECT name, details FROM recent_properties";
$result = $mysqli->query($query);
if($result->num_rows()>0)
{
$html = "<table>";
$html .= '<tr><th>Name</th><th>Details</th></tr>';
while ($row = $result->fetch_assoc()) {
$html .= '<tr>';
$html .= '<td>' . $row["name"] . '<td>';
$html .= '<td>' . $row["details"] . '<td>';
$html .= '</tr>';
}
$html .= "</table>";
echo $html;
}
$mysqli->close();
this is the simplest way to create HTML content from data
in your case you can do some thing like this
if ($result->num_rows() > 0) {
$dataArray = [];
while ($row = $result->fetch_assoc()) {
$dataArray[$row["name"]] = $row["details"];
}
}
and then use the array in your HTML
<body>
<p><?php echo 'a: ' . $arrayData['a'] ?></p>
<p><?php echo 'b: ' . $arrayData['b'] ?></p>
<p><?php echo 'c: ' . $arrayData['c'] ?></p>
</body>

You need to loop through your $result and fetch an associative array:
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["name"], $row["details"]);
}
EDIT:
while ($row = $result->fetch_assoc()) {
echo '<p>'.$Name1.': '.$Details1.'</p>';
// Whatever else in this section
// You can even break out of PHP and then
// get back into PHP again if you have a lot of HTML.
}

Related

how to output mysql table data into an html table without knowing what $row is like phpmyadmin

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,

How to remove selected columns from dynamically generated html-table?

I have an SQL-database where I read out data that are then shown in a dynamically generated html-table. Here is my code that works fine:
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray";
$result = mysqli_query($db, $sql) or die("Invalid query");
$numrows = mysqli_num_rows($result);
$numcols = mysqli_num_fields($result);
$field = mysqli_fetch_fields($result);
if ($numrows > 0) {
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th>" . 'Nr' . "</th>";
for($x=0;$x<$numcols;$x++){
echo "<th>" . $field[$x]->name . "</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
$nr = 1;
while ($row = mysqli_fetch_array($result)) {
echo "<td>" . $nr . "</td>";
for ($k=0; $k<$numcols; $k++) {
echo "<td>" . $row[$k] . "</td>"; //Prints the data
}
$nr = $nr + 1;
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
}
mysqli_close($db);
Now, I want to remove specific columns (e.g. those, which are empty or those, which are not that interesting for the user, who makes the request).
I tried it with unset($field[$variable]), however, it didn't work. In addition, the values (if there are any), should be removed, too.
can let mysql filter them out for you,
$sql = "SELECT $selection FROM $tabelle WHERE $masterarray AND LENGTH($selection) > 0";
-- http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_length
Always format the array before you print it. Try to remove the specific columns from the $field array before you echo the HTML and then print the final table. Once the HTML code is echoed in PHP you won't be able to remove it without the use of JavaScript.
You can check against the $field[$x]->name variable and use continue to skip the column.
<?php
// DataBase Config - http://php.net/manual/pt_BR/pdo.construct.php.
$dsn = 'mysql:host=localhost;dbname=test';
$usr = 'root';
$pwd = '';
try { // try to connect in database.
$pdo = new PDO($dsn, $usr, $pwd);
} catch (PDOException $e) { // if there is error in the connection.
die('Connection failed: ' . $e->getMessage());
}
// Prepare Statement and execute - http://php.net/manual/pt_BR/pdo.prepare.php.
$stm = $pdo->prepare('select id, weight, color, name from product');
$stm->execute();
// Get ALL rows - Object.
$rows = $stm->fetchAll(PDO::FETCH_OBJ);
// Print Rows.
//echo '<pre>'.print_r(rows, true).'</pre>';
// Check $row;
if (count($rows)) {
// Order and Display Cols.
$colsDisplay = [
'id' => 'ID Product',
'name' => 'Name',
'weight' => 'Weigth'
];
// Table.
$html = '<table border="1">';
$html .= "\n <thead>";
$html .= "\n <tr>";
$html .= "\n <th bgcolor='#eee'>Row</th>";
$html .= "\n <th>". implode("</th>\n <th>", $colsDisplay) ."</th>";
$html .= "\n </tr>";
$html .= "\n </thead>";
$html .= "\n <tbody>";
// Loop ROWS.
foreach ($rows as $key => $val) {
$html .= "\n <tr>";
$html .= "\n <td bgcolor='#eee'>". $key ."</td>";
// Loop COLS to display.
foreach ($colsDisplay as $thKey => $thVal) {
$html .= "\n <td>". $val->$thKey ."</td>";
}
$html .= "\n </tr>";
}
$html .= "\n".' </tbody>';
$html .= "\n".'</table>';
echo $html;
}
In order to know that a column is empty, you should check the whole column. There are different ways to do it, one of them could be investigating which of them are empty and then only using those that aren't empty. Something like this:
<?php
// ...
$q = "SELECT SUM(LENGTH(my_first_column)) col_0, SUM(LENGTH(my_second_column)) col_1, ..., SUM(LENGTH(my_11th_column)) col_10 FROM $tabelle WHERE $masterarray";
// ... execute query and return results in $nonEmpty
$nonEmpty = array();
foreach($row as $columnIndex) {
if ($row[$columnIndex] > 0) {
$nonEmpty[] = $columnIndex;
}
}
// ... now go through results and print only cols with at least one row with lenght > 0 i.e. non empty
$len = 11;
$rowHTML = "<tr>";
while ($row = mysqli_fetch_array($result)) {
for ($i = 0; $i < $len; ++$i) {
$rowHTML = '';
if (!in_array($i, $nonEmpty)) {
$rowHTML .= '<td>' . $row[$i] . '</td>';
}
$rowHTML .= "</tr>\n";
}
}
// ...
This chunk of code will remove columns with ALL empty values. If you have at least one cell in the column with some value, you'll see the column in your result.
The code isn't optimized - it's just a rough idea. But it's a starting point.

Cannot get URL from Database to link

I am doing a project and would be eternally grateful for help in getting my URl's to link. I have tried looking around to no avail. I have a database (4columns). The last one (link1) should link to videos with the specified URL.When the table comes up the URL's are not clickable (is there a way to simplify this say "click me"?). Here is my code. I've also attached an image of the table. This is really busting my brains, thanks.
<?php
$con = mysqli_connect("localhost","feedb933_charles","pass100","feedb933_test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM videos";
$result = mysqli_query($con, $sql);
echo "<table>";
echo "<tr>
<th>topic1</th>
<th>subject1</th>
<th>link1</th>
</tr>";
while( $row = mysqli_fetch_array( $result)) {
$topic1 = $row["topic1"];
$subject1 = $row["subject1"];
$link1 = $row["link1"];
echo "<tr>
<td>$topic1</td>
<td>$subject1</td>
<td>$link1</td>
</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Table output
Try this:
<?php
$sql = "SELECT * FROM `videos`";
$result = mysqli_query($con, $sql);
?>
<table>
<?php
while($row = mysqli_fetch_assoc( $result)) {
?>
<tr>
<td><?php echo $row['topic1'];?></td>
<td><?Php echo $row['subject1'];?></td>
<td><a href="<?php echo $row['link1']; ?>" target="_blank">Click me</td>
</tr>
<?php } ?>
<table>
Or you can also use do while loop:
do{
echo '<tr>';
echo '<td>'.$row['topic1'].'</td>';
echo '<td>'.$row['subject1'].'</td>';
echo '<td><a href="'.$row['link1'].'" target="_blank">Click me</td>';
echo '</tr>';
} while($row = mysqli_fetch_assoc( $result);
I added the target attribute to open the link in a new window.
I looked at your code and i found a couple errors.
change $con = mysqli_connect("localhost","feedb933_charles","pass100","feedb933_test"); to $con = new mysqli("localhost", "feedb933_charles", "pass100", "feedb933_test");
Then change if (mysqli_connect_errno()) to if (mysqli_connect_error()) {
Then change
$sql = "SELECT * FROM videos";
to
$sql = "SELECT topic1, subject1, link1 FROM videos";
or if you want to select one row
$differentvalue = ""; // value to run
$sql = "SELECT topic1, subject1, link1 FROM videos WHERE difvalue = ?";
difvalue is the value different frm the rest so the php code knows what to grab.
Using stmt means no sql injection
Add:
$stmt = $con->stmt_init();
if (!$stmt->prepare($sql))
{
print "Failed to prepare statement\n";
}
else
{
}
Then in side if (something) { } else { IN HERE }
(if you have WHERE diffvalue) Add:
$stmt->bind_param("s", $differentvalue); // $stmt->bind_param("s", $differentvalue); if text, $stmt->bind_param("i", $differentvalue); if integer
Then
Add:
$stmt->execute();
$list = $stmt->fetchAll();
then outside the if (something) { code } else { code }
Add:
echo "<table><tr><th>topic1</th><th>subject1</th><th>link1</th></tr><tr>";
foreach ($list as $row => $new) {
$html = '<td>' . $new['topic1'] . '</td>';
$html .= '<td>' . $new['subject1'] . '</td>';
$html .= '<td>' . $new['link1'] . '</td>';
echo $html;
}
echo "</tr></table>";
If you are still having problems goto the links listed
http://php.net/manual/en/pdostatement.fetchall.php
http://php.net/manual/en/mysqli-stmt.get-result.php
http://php.net/manual/en/mysqli-result.fetch-all.php
Hope this helps
<?php
$con=mysqli_connect("localhost","feedb933_charles","pass100","feedb933_test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT * FROM videos";
$result = mysqli_query($con, $sql);
echo "<table>";
echo "<tr>
<th>topic1</th>
<th>subject1</th>
<th>link1</th>
</tr>";
while( $row = mysqli_fetch_array( $result)) {
$topic1 = $row["topic1"];
$subject1 = $row["subject1"];
$link1 = $row["link1"];
echo "<tr>
<td>$topic1</td>
<td>$subject1</td>
<td>$link1</td>
*//this href will give u the link as u asked. //be sure you store proper url. In case of exact video name saved in column thn can make the url for your web output. //ex:<a href="http://example.com/'.$link.'.extension">*
</tr>";
}
echo "</table>";
mysqli_close($con);
?>

First array from query PHP

I have a problem with my code. I want to get the first array from query and show it, after what show the next 2.
For the first Array in query I want to show img for the next 2 only the title
My code:
$link = mysql_connect('server', 'user', 'password')
or die("Can't");
$db = mysql_select_db('database')
or die ("can't");
$sql = 'SELECT * FROM News LIMIT 3';
$retval = mysql_query($sql,$link);
$filename ="footer.html";
$handle = fopen("footer.html", 'w+');
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
//echo "<pre>"; print_r($row); echo "</pre>";
$content = '<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<div class="block_articles">
<div class="block_header" >
<div class="headerlink" >
<a href="'.$sitelink.'" target="_blank"></div></div>';
$content .= '<img src="'.$sitelink.'news/'.$row['ImageName'].'" alt="'.htmlspecialchars($row['Title']).'" >';
$content .= ''.$row['Title'].'';
$content .= '<div class="date">';
$content .= $row['Date'];
$content .= '</div>';
$content .= '</div>';
echo $row['Title'].'<br>';
if ($handle)
{
if (!fwrite($handle, $content))
die("can't");
}
}
Based on your comments, you want to use a basic loop counter and change the behavior based on the counter:
theCurrentRow = 0;
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
theCurrentRow++;
if (theCurrentRow == 1) {
//show the images
}
else {
// show the title
}
}
Also to reiterate #AmalMurali's comment: don't use mysql_* functions, they're deprecated: http://php.net/manual/en/mysqlinfo.api.choosing.php

Displaying all tables in a database

How do I display out all the information in a database (All tables and records) using PHP? I read displaying tables as HTML table but how do I do it for all the tables?
I tried the example here:
http://davidwalsh.name/html-mysql-php
But it shows the table names, how do I also display all the values?
Okay got it .. try this
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "username", "password", "DB");
$result = $mysqli->query("SHOW TABLES");
while ($row = $result->fetch_row()) {
$table = $row[0];
echo '<h3>', $table, '</h3>';
$result1 = $mysqli->query("SELECT * FROM `$table`");
echo '<table cellpadding="0" cellspacing="0" class="db-table">';
$column = $mysqli->query("SHOW COLUMNS FROM `$table`");
echo '<tr>';
while ($row3 = $column->fetch_row()) {
echo '<th>' . $row3[0] . '</th>';
}
echo '</tr>';
while ($row2 = $result1->fetch_row()) {
echo '<tr>';
foreach ($row2 as $key => $value) {
echo '<td>', $value, '</td>';
}
echo '</tr>';
}
echo '</table><br />';
}
$mysqli->close();
you can use the recursive function to display the tree Structure of your database.
Here is the a sample code from http://webcodingeasy.com/PHP/Simple-recursive-function-to-print-out-database-tree-structure
<?php
function print_menu($id = 0)
{
// get all records from database whose parent is $id
$result = $query->select_result("*", "table", "where parent = '".$id."'");
//check if there are any results
if($result != 0)
{
echo "<ul> n";
while($row = $query->fetch($result))
{
//print result and call function to check if it has children
echo "<li>".$row['name']."</li> n";
print_menu($row['ID']);
}
echo "</ul> n";
}
}
print_menu();
?>
If you want to pull all tables with the values in mysql, you can use the following code:
<?php
mysql_connect ("localhost", "DB_USER", "DB_PASSWORD"); //your mysql connection
mysql_select_db('DB_NAME') or die( "Unable to select database"); //your db name
$tables = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema='DB_NAME'"); //pull tables from theh databsase
while ($table= mysql_fetch_row($tables)) {
$rsFields = mysql_query("SHOW COLUMNS FROM ".$table[0]);
while ($field = mysql_fetch_assoc($rsFields)) {
echo $table[0].".".$field["Field"].", "; //prints out all columns
}
echo $table[0];
$query = "SELECT * FROM ".$table[0]; //prints out tables name
$result = mysql_query($query);
PullValues($result); //call function to get all values
}
//function to pull all values from tables
function PullValues($result)
{
if($result == 0)
{
echo "<b>Error ".mysql_errno().": ".mysql_error()."</b>";
}
elseif (#mysql_num_rows($result) == 0)
{
echo("<b>Query completed. No results returned.</b><br>");
}
else
{
echo "<table border='1'>
<thead>
<tr><th>[Num]</th>";
for($i = 0;$i < mysql_num_fields($result);$i++)
{
echo "<th>" . $i . " - " . mysql_field_name($result, $i) . "</th>";
}
echo " </tr>
</thead>
<tbody>";
for ($i = 0; $i < mysql_num_rows($result); $i++)
{
echo "<tr><td>[$i]</td>";
$row = mysql_fetch_row($result);
for($j = 0;$j < mysql_num_fields($result);$j++)
{
echo("<td>" . $row[$j] . "</td>");
}
echo "</tr>";
}
echo "</tbody>
</table>";
} //end else
}
?>
I am using this and works fine in mysql, for mysqli you need to tweak it a very little.

Categories