Weird data output about PHP & MySQL - php

It's wired that only Field name is correct but others. I can't get the the expected result from the code.
How get the correct meta data from the database?
The expected result
Actual result
<?php
// Open a connection to the server and USE the winestore
$link = mysqli_connect("localhost","root","","winestore");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Run a query on the wine table in the winestore database to retrieve
// one row
$query = "SELECT * FROM wine LIMIT 1";
$result = mysqli_query($link, $query);
// Output a header, with headers spaced by padding
print "\n" .
str_pad("Field", 20) .
str_pad("Type", 14) .
str_pad("Null", 6) .
str_pad("Key", 5) .
str_pad("Extra", 12) . "\n";
// How many attributes are there?
$x = mysqli_num_fields($result);
// for each of the attributes in the result set
for($y=0;$y<$x;$y++)
{
// Get the meta-data for the attribute
$info = mysqli_fetch_field ($result);
// Print the attribute name
print str_pad($info->name, 20);
// Print the data type
print str_pad($info->type, 6);
// Print the field length in brackets e.g.(2)
print str_pad("({$info->max_length})", 8);
// Print out YES if attribute can be NULL
if ($info->not_null != 1)
print " YES ";
else
print " ";
// Print out selected index information
if ($info->primary_key == 1)
print " PRI ";
elseif ($info->multiple_key == 1)
print " MUL ";
elseif ($info->unique_key == 1)
print " UNI ";
// If zero-filled, print this
if ($info->zerofill)
print " Zero filled";
// Start a new line
print "\n";
}
mysqli_free_result($result);
mysqli_close($link);
?>

As per the query the expected result is the detail of the table structure and for that one can use mysql Describe table query which will provide the structure of the table.
<?php
$con = mysqli_connect(HOST,USER,PASSWORD,DATABASE NAME);
$data = mysqli_query($con,"DESCRIBE tablename");
?>
<table>
<tr>
<td>Field</td>
<td>Type</td>
<td>Null</td>
<td>Key</td>
<td>Default</td>
<td>Extra</td>
</tr>
<?php while($row=mysqli_fetch_array($data,MYSQLI_ASSOC)){ ?>
<tr>
<td><?php echo $row['Field']; ?></td>
<td><?php echo $row['Type']; ?></td>
<td><?php echo $row['Null']; ?></td>
<td><?php echo $row['Key']; ?></td>
<td><?php echo $row['Default']; ?></td>
<td><?php echo $row['Extra']; ?></td>
</tr>
<?php } ?>
</table>
As per the query the expected result is the detail of the table structure and for that one can use mysql Describe table query which will provide the structure of the table.

you can try following code.I think it will help you.
<?php
error_reporting(0);
$conn = mysqli_connect('localhost', 'root', '');
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('winestore');
$result = mysql_query('SELECT * FROM wine LIMIT 0,1');
if (!$result) {
die('Query failed: ' . mysql_error());
}
?>
<table>
<th>Field</th>
<th>Type</th>
<th>Null</th>
<th>Key</th>
<th>Extra</th>
<?php
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
$meta = mysql_fetch_field($result, $i);
if (!$meta) {
echo "No information available<br />\n";
}
$i++;
?>
<tr>
<td><?php echo $meta->name;?></td>
<td><?php echo $meta->type."(".$meta->max_length.")";?></td>
<td><?php if($meta->not_null==1){echo 'NO';}else{echo 'YES';}?></td>
<td><?php if($meta->multiple_key==1){ echo 'MUL';}if($meta->primary_key==1){echo 'PRI';}?></td>
<td><?php echo $meta->not_null;?></td>
</tr>
<?php
}
mysql_free_result($result);
?>
if you have any more doubt about this issue,please visit this link http://php.net/manual/en/function.mysql-fetch-field.php

Related

How do I display different table from 1 table? Like each table has unique code

This are my db table:
But my query only get 1 row for each table like this:
As you can see, there are 2 tables for 1003 because it has 2 rows. It should be only one (1) table of 1003 with 2 rows. How do I fix this? EXPECTED RESULT:
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone GROUP BY model";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $row["model"]?></td>
</tr>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
You have at least 5 problems here,
[edit: problem 1 removed & changed sample based on extended answer]
Inside your while { ... } loop, you're printing an entire table, when you should only be printing the <tr>...</tr> part there. This is what causes additional table(s).
And 3rd problem: your "no_record" line is a loose <td>. Not only isn't it inside the table (which is covered in problem #2), it's also not wrapped with a <tr>.
4th problem: You're randomly printing the echo $row["brand_code"] outside of the table.
5th problem: you're printing raw data from the database as if it is valid html, it more than likely is not. it has to be probably encoded with htmlentities/htmlspecialchars.
Quick & dirty fixed version:
function tableOpen($row) {
printf( '<h1>%s</h1>', htmlentities($row["brand_code"]) );
echo '<table id="table_stock" class="">';
echo '<thead>';
echo '<tr>';
echo '<th>Model</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
}
function tableClose() {
echo '</tbody>';
echo '</table><br>';
}
// Attempt select query execution
$query = "SELECT model, brand_code FROM smartphone ORDER BY brand_code";
$lastBrand = null;
if ($result = mysqli_query($db, $query)) {
if (mysqli_num_rows($result) > 0) {
if ($lastBrand !== $row["brand_code"] && !is_null($lastBrand)) tableClose();
if ($lastBrand !== $row["brand_code"]) tableOpen($row);
$lastBrand = $row["brand_code"];
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
printf( '<td>%s</td>', htmlentities($row["model"]) );
echo '</tr>';
}
tableClose();
/// Free result
mysqli_free_result($result);
} else {
echo '<p class="no_record">No records found.</p>';
}
} else {
echo "ERROR: Not able to execute \$query: <br>" . htmlentities($query) . '<br>' . htmlentities(mysqli_error($link));
}
you need additional loop. Also in the first query you need to use group by codes.
$query = "SELECT model, brand_code FROM smartphone GROUP BY brand_code";
if($result = mysqli_query($db, $query))
{
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<?php echo $row["brand_code"]?>
<table id="table_stock" class="">
<thead>
<tr>
<th>Model</th>
</tr>
</thead>
<tbody>
<?php
if ($result1 = mysqli_query($db, "SELECT DISTINCT model, brand_code FROM smartphone WHERE brand_code={$row["brand_code"]}"))
{
while ($row1 = mysqli_fetch_array($result1))
{
// get count for each model within brand_code
$cnt = ($result2 = mysqli_query($db, "SELECT COUNT(*) AS cnt FROM smartphone WHERE brand_code={$row["brand_code"]} AND model='{$row1["model"]}'")) && ($row2 = mysqli_fetch_array($result2)) ? $row2["cnt"] : "---";
?>
<tr>
<td><?php echo $row1["model"] ({$cnt})?></td>
</tr>
<?php
}
mysqli_free_result($result1);
}
?>
</tbody>
</table><br>
<?php
}
/// Free result
mysqli_free_result($result);
}
else
{
echo "<td class='no_record' colspan='7'>No records found.</td>";
}
}
else
{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}

Explode string from table and compare output with other table

Hello my first question here, I have a bad of trouble getting this code to work or better said how to proceed.
I have 2 tables, table 1 holds a string separated by commas, after exploding the array I want to compare the strings to another table that holds product prices related to the string.
<?php
function packages()
{
global $db;
$query = "SELECT * FROM product_package WHERE package_id > 1; ";
$result = mysqli_query($db, $query) or die('<h3>Query failed</h3>');
$rowcount = mysqli_num_rows($result);
if ($rowcount < 1)
{
return;
}
else
{
while ($row = mysqli_fetch_array($result))
{
$singles = explode(',', $row["product_ids"]);
$query2 = "SELECT product_price FROM products WHERE product_id = $single; ";
$result2 = mysqli_query($db, $query2);
?>
<tr>
<td><?php echo $row["package_id"] ?></td>
<td><?php echo $row["package_name"] ?></td>
<td><?php echo $row["product_ids"] ?></td>
<td>
EDIT
</td>
<td>
<?php
foreach($singles as $single)
{
echo $single . '<br />';
}
?>
</td>
</tr>
<?php
}
}
}
?>
How do I echo the prices that are overlapping with $single?

Repopulate a table of results with results that match a search

I have the following code which echoes out pupil info from a database automatically. However when the user searches for a specific pupil I need to repopulate the same table with relevant pupils to the search request.
All help is greatly appreciated!
if(!isset ($_POST['search'])){
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0 ) {
$totalpupil = "There are currently no Pupils in the system.";
} else{
while($row = mysql_fetch_array($pupils)){
?>
<tr>
<td><?php echo ''.$row['pupil_id'].''; ?></td>
<td><?php echo $row['pupil_name']?></td>
<td><?php echo $row['class_id']?></td>
<td>Edit | Delete</td>
</tr>
<?php
}
}
}
Something like this ?
if(!isset ($_POST['search'])){
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
}
elseif(isset($_POST['search'])){
$search_param = "%".$_POST['search']."%";
$pupils = mysql_query("SELECT * FROM pupil WHERE LOWER(pupil_name) LIKE LOWER($search_param)") or die("Cant find Pupils");
}
$count = mysql_num_rows($pupils);
if($count == 0){
$totalpupil = "There are currently no Pupils in the system.";
}
else{
while($row = mysql_fetch_array($pupils)){
?>
<tr>
<td><?php echo ''.$row['pupil_id'].''; ?></td>
<td><?php echo $row['pupil_name']?></td>
<td><?php echo $row['class_id']?></td>
<td>Edit | Delete</td>
</tr>
<?php
}
I'm assuming that you are searching in the pupil_name column.

Using MySql to populate a html table using a specific column

Essentially, I am creating a movie ordering system that has 7 movie genres, and I want each movie tab to populate according to genre. At this point I cant even get the table to show up. Can anyone help me out?
<div id="content">
<table>
<tr><th>Name</th> <th>Genre</th> <th>Year</th> <th>Rating</th></tr>
<?php
//connect to database
$dbc = mysql_connect('localhost' , 'username' , 'password');
$test = mysql_select_db('movies', $dbc);
if ($test = mysql_select_db('movies', $dbc))//test
{
$query = "SELECT * FROM 'movies' WHERE 'genre' = 'Action'";
//call query
$result = mysql_query($query, $dbc);
while ($row = mysql_fetch_array($result))
{
?>
<tr>
<td><?php print $row['name']; ?></td>
<td><?php print $row['genre']; ?></td>
<td><?php print $row['year']; ?></td>
<td><?php print $row['rating'];?></td>
</tr>
<table>
<?php
}//close the while loop
}//close the if statement
mysql_close($dbc);
?>
First of all, do not use mysql because of secure problems and it will be not suported in PHP later. Read about this http://php.net/manual/en/function.mysql-connect.php .
Try to use PDO or mysqli, for example :
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 'movies' WHERE 'genre' = 'Action'");
while($row = mysqli_fetch_array($result))
{
echo $row['name'];
echo "<br>";
}
mysqli_close($con);

Display result from database in two columns

EDIT: This is what I am trying to achieve: http://i.imgur.com/KE9xx.png
I am trying to display the results from my database in two columns. I'm a bit new to PHP so I haven't the slightest clue on how to do this. Can anybody help me with this? Thanks in advance.
Here is my current code:
include('connect.db.php');
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM todo ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
// display records in a table
echo "<table width='415' cellpadding='0' cellspacing='0'>";
// set table headers
echo "<tr><td><img src='media/title_projectname.png' alt='Project Name' /></td>
<td><img src='media/title_status.png' alt='Status'/></td>
</tr>";
echo "<tr>
<td><div class='tpush'></div></td>
<td> </td>
</tr>"
while ($row = $result->fetch_object())
{
echo "<tr>";
echo "<td><a href='records.php?id=" . $row->id . "'>" . $row->item . "</a></td>";
echo "<td>" . $row->priority . "</td>";
echo "</tr>";
}
echo "</table>";
}
// if there are no records in the database, display an alert message
else
{
echo "No results to display!";
}
}
// show an error if there is an issue with the database query
else
{
echo "Error: " . $mysqli->error;
}
// close database connection
$mysqli->close();
A good idea would be storing your data into a simple array and then display them in a 2-columned table like this:
$con = mysql_connect('$myhost', '$myusername', '$mypassword') or die('Error: ' . mysql_error());
mysql_select_db("mydatabase", $con);
mysql_query("SET NAMES 'utf8'", $con);
$q = "Your MySQL query goes here...";
$query = mysql_query($q) or die("Error: " . mysql_error());
$rows = array();
$i=0;
// Put results in an array
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
$i++;
}
//display results in a table of 2 columns
echo "<table>";
for ($j=0; $j<$i; $j=$j+2)
{
echo "<tr>";
echo "<td>".$row[$j]."</td><td>".$row[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
<table>
<tr>
<td>ProjectName</td>
<td>Status</td>
<td>ProjectName</td>
<td>Status</td>
</tr>
<?php
while($row = $result->fetch_object()) {
echo "<tr>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "<td>".$row->ProjectName."</td>";
echo "<td>".$row->Status."</td>";
echo "</tr>";
}
?>
</table>
This is the thing on picture. With a bit CSS you can manipulate the tds.
Your function should look similar to this:
$query = "SELECT *
FROM todo
ORDER BY id";
$result = $mysqli->query($query);
while($row = $result -> fetch_array()) {
$feedback .= "<tr>\n<td>" . $row['item'] . "</td><td>" . $row['priority'] . "</td>\n</tr>";
}
return $feedback;
Then, in your HTML have the <table> already setup and where you would normally insert your <td> and <tr> put <?php echo $feedback?> (where $feedback is the assumed variable on the HTML page that retrieves the $feedback from the function). This isn't a complete fix, your code is hard to read, but by starting here, you should be able to continue on the path filling in all the extra information you need for the table, including your CSS.

Categories