I'm trying to get a php to pull all records from a mysql db, and display them formatted. For some reason the 1st record displays correctly, but the 2nd record that displays directly below it does not show the field name. What am I doing wrong?
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '***';
$database = 'db';
$table = 'upstable';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table}"); // sending query
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
while($row = mysql_fetch_row($result)) // printing table rows
{
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[0]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[1]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[2]v</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[3]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[4]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[5]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[6]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[7]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</div></b><div id='column2'>$row[8]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[9]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[10]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[11]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[12]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[13]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[14]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[15]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column2'><b>{$field->name}:</b></div><div id='column2'>$row[16]</div><br>";
$field = mysql_fetch_field($result);
echo "<div id='column'><b>{$field->name}:</b></div><div id='column'>$row[17]</div><br><br><br>";
$row = 0;
}
mysql_free_result($result);
?>
UPDATED:
ALMOST fixed, but it's not quite right. It is making each complete set of data alternating backgrounds (the class "column2" is grey and "columnn" is white), rather than every other row in each set. Does that make more sense?
This is what I'm using right now, what should I change?
$row_num = 0;
$css_classes[0] = 'column2';
$css_classes[1] = 'column';
while($row = mysql_fetch_assoc($result))
{
$row_num++;
$class = $css_classes[$row_num % 2];
foreach ($row as $col_name => $col_val)
{
echo "<div class='$class'><b>{$col_name}:</b></div><div class='$class'>$col_val</div><br>";
}
echo "<br><br>";
Below code should work perfectly, and has more readibility.
while($row = mysql_fetch_assoc($result))
{
foreach ($row as $col_name => $col_val)
{
echo "<div id='column2'><b>{$col_name}:</b></div><div id='column2'>$col_val</div><br>";
}
}
Updated
Well, I'm not good at HTML/CSS. I would like to to like this if I were you.
$row_num = 0;
$css_classes[0] = 'gray_style';
$css_classes[1] = 'white_style';
while($row = mysql_fetch_assoc($result))
{
$row_num++;
$class = $css_classes[$row_num % 2];
foreach ($row as $col_name => $col_val)
{
echo "<div id='column2' class='$class'><b>{$col_name}:</b></div><div id='column2'>$col_val</div><br>";
}
}
You're only fetching the first row(because $results default position is [0], which is the first row.).
you obviously don't understand the process involved in fetching sorting, and displaying data with php, but here's an example of a prepared statement and a normal query using mysqli.
mysqli query
function getmarkets()
{
global $mysqli;
$query = $mysqli->query("SELECT pair, last_price FROM all_currency_data");
$num_rows = $query->num_rows;
if($num_rows > 0) {
while($row = $query->fetch_assoc())
{
$mkt = explode("-",$row["pair"]);
$coin = $mkt[0];
$base = $mkt[1];
echo '<a class="animate" href="?p=trade&market='.urlencode($row["pair"]).'" style="text-decoration: none;"><li class="mkt-normal" id="'.$row["pair"].'_div">'.$coin.'/'.$base.' <span class="price" id="'.$row["pair"].'_price">'.$row["last_price"].'</span></li></a>';
}
$query->close();
}
}
prepared statement
$stmt = $mysqli->prepare("SELECT user,message,timestamp FROM uc_support_replies WHERE tickethash = ? ORDER BY timestamp ASC");
$stmt->bind_param('s',$ticket);
$stmt->execute();
$stmt->bind_result($user,$message,$timestamp);
while($stmt->fetch())
{
if(in_array($user, $admins)) {
$color = '0404B4';
}else{
$color = '2E2E2E';
}
$output .=
'
<div class="msgdiv">
<hr class="five">
<span class="user_name" style="color:#'.$color.'"><u>'.$user.'</u></span>
</br>
<span class="user_message">'.$message.'</span>
</br>
<span data-livestamp="'.$timestamp.'">'.$timestamp.'</span>
<hr class="five">
</div>
';
}
The MySQL extension was officially deprecated since PHP 5.5.0 in late 2012 and it will be removed in the future. Recommended alternative since PHP 5 and later is MySQLi ("i" stands for "improved"). http://www.php.net/manual/en/book.mysqli.php
Related
I'm trying to make a code that permits the user to show any table in my database in a php page.
I tried with that code:
<?php
include('connection_db.php');
$table = $_POST['table'];
$sql1 = "SELECT * FROM $table";
$sql2 = "SELECT count(*)
FROM information_schema.columns
WHERE table_name = '$table'";
$sql3 = "SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'$table'";
$result = mysql_query($sql1);
$column = mysql_query($sql2);
$ncolumn= mysql_query($sql3);
echo "<table width='100%' border='1'>";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
for ($i = 0; $i <= $column; $i++) {
echo "<td>". $row['$ncolumn'] ."</td>";
}
echo "</tr>";
echo "<br/>";
}
echo "</table>";
?>
It should show the entire table with his records, but it shows only a lot of empty lines
$table = $_POST['table'];
$mysqli = new mysqli(_DB_SERVER_,_DB_USER_,_DB_PASSWD_,_DB_NAME_);
$mysqli->set_charset("utf8");
if (mysqli_connect_errno()) {
$Message = "Connect failed: %s\n" . $mysqli->connect_error;
exit();
}
if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
if($result->num_rows == 1) {
$Tableexists = "yes";
} else {
$Tableexists = "no";
}
} else {
$Tableexists = 0;
}
echo $Tableexists;
I am trying to add a character before/after value in mysql query. but I can't make it work.
This is the part that doesn't work in my case:
$query = "select CONCAT ('.', DuRpt) as DuRpt, DaRpt from DDtb order by DATE DESC";
You can see the full code below. Any ideas why it doesn't work or can I get an alternative solution, please. thanks.
<div class="container">
<div class="left">
<?php
include ("etc/config.php");
$query = "select concat ('.', DuRpt) as DuRpt, DaRpt from DDtb order by DATE DESC";
$result = mysqli_query($link, $query);
if (!$result) {
$message = 'ERROR:' . mysqli_error($link);
return $message;
} else {
$i = 0;
echo '<form name="select" action="" method="GET">';
echo '<select name="mySelect" id="mySelect" size="44" onchange="this.form.submit()">';
while ($i < mysqli_field_count($link)) {
$meta =
mysqli_fetch_field_direct($result, $i);
echo '<option>' . $meta->name . '</option>';
$i = $i + 1;
}
echo '</select>';
echo '</form>';
}
?>
</div>
<div>
<?php
if(isset($_GET['mySelect'])) {
$myselect = $_GET['mySelect'];
$sql = "SELECT `$myselect` as mySelect from DDtb order by DATE DESC";
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
$table_row_counter = 3;
echo '<table>';
while($row = $result->fetch_assoc())
{
$table_row_counter++;
if ($table_row_counter % 30 == 1) {
echo '</table>';
echo '<table>';
}
echo "<tr><td>" . $row["mySelect"] . "</td></tr>";
}
}
}
echo '</table>';
mysqli_close($link);
?>
</div>
</div>
For the 2nd half of your code, you can do this:
note you won't need to concat anything in your initial query
if(isset($_GET['mySelect'])) {
// configure every option here, if there's not pre/postfix, use a blank string
$prepostfixes = [
'DuRpt' => ['.', '.'],
'DaRpt' => ['', ''],
];
$myselect = $_GET['mySelect'];
if (!isset($prepostfixes[$myselect])) {
die ('Unknown Select'); // this will prevent sql injection
}
$sql = "SELECT `$myselect` as mySelect from DDtb order by DATE DESC";
$result = mysqli_query($link, $sql);
if ($result->num_rows > 0) {
$table_row_counter = 3;
echo '<table>';
$prefix = $prepostfixes[$myselect][0];
$postfix = $prepostfixes[$myselect][1];
while($row = $result->fetch_assoc())
{
$table_row_counter++;
if ($table_row_counter % 30 == 1) {
echo '</table>';
echo '<table>';
}
echo "<tr><td>" . $prefix . $row["mySelect"] . $postfix . "</td></tr>";
}
}
}
Just update your code and remove the duplicate of DuRpt from it.
$query = "select concat ('.', DuRpt) as DuRpt from DDtb order by DATE DESC";
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.
}
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.
Is this OK ?
$i = 0;
while ($row = mysql_fetch_array($result))
{
$resultset[] = $row;
$columns[] = mysql_fetch_field($result, $i);
}
Then when trying to print
<tr><th><?php echo $columns[0] ?></th><th><?php echo $columns[1] ?></th></tr>
I got an error
Catchable fatal error: Object of class stdClass could not be converted to string
Try the mysql_fetch_field function.
For example:
<?php
$dbLink = mysql_connect('localhost', 'usr', 'pwd');
mysql_select_db('test', $dbLink);
$sql = "SELECT * FROM cartable";
$result = mysql_query($sql) or die(mysql_error());
// Print the column names as the headers of a table
echo "<table><tr>";
for($i = 0; $i < mysql_num_fields($result); $i++) {
$field_info = mysql_fetch_field($result, $i);
echo "<th>{$field_info->name}</th>";
}
// Print the data
while($row = mysql_fetch_row($result)) {
echo "<tr>";
foreach($row as $_column) {
echo "<td>{$_column}</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Use mysql_fetch_assoc to get only an associative array and retrieve the column names with the first iteration:
$columns = array();
$resultset = array();
while ($row = mysql_fetch_assoc($result)) {
if (empty($columns)) {
$columns = array_keys($row);
}
$resultset[] = $row;
}
Now you can print the head of your table with the first iteration as well:
echo '<table>';
$columns = array();
$resultset = array();
while ($row = mysql_fetch_assoc($result)) {
if (empty($columns)) {
$columns = array_keys($row);
echo '<tr><th>'.implode('</th><th>', $columns).'</th></tr>';
}
$resultset[] = $row;
echo '<tr><td>'.implode('</td><td>', $rows).'</td></tr>';
}
echo '</table>';
You want to look at
mysql_fetch_assoc
Which gives each row as an associative key => value pair where the key is the column name.
Documentation here
Here is a more modern solution with ...i:
$db_link = #mysqli_connect($server, $user, $pass, $db) or die("Connection failed");
$spalten = ['pc_name', 'pc_type', 'pc_snr', 'pc_bj', 'mo_port_1', 'mo_snr_1', 'mo_bj_1', 'mo_port_2', 'mo_snr_2', 'mo_bj_2'];
$abfrage = "SELECT " . implode(',', $spalten) . " FROM hardware order by pc_name";
$liste = mysqli_query($db_link, $abfrage);
$spalten = mysqli_num_fields($liste);
while ($werte[] = mysqli_fetch_array($liste, MYSQLI_ASSOC)) {}
<table class="display" id="table" style="width:100%">
<thead>
<tr>
<?php
for ($i = 0; $i < $spalten; $i++) {
$feldname[$i] = mysqli_fetch_field_direct($liste, $i)->name;
echo '<th>' . ucfirst($feldname[$i]) . '</th>';
}
?>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < mysqli_num_rows($liste); $i++) {
?>
<tr>
<?php for ($j = 0; $j < $spalten; $j++) {
?>
<td><?php
echo $werte[$i][$feldname[$j]];
?>
</td>
<?php } ?>
</tr>
<?php } ?>
</tbody>
</table>
Though it's deprecated and no longer in PHP 7 you can avoid having to use an object by using the function mysql_field_name instead which returns a string.