Re-factoring this mysql table display code - php

I'm not wholly proficient with PHP but I'm having a few problems echoing a gathered value from a MySQL query function.
I believe I know where the problem lies but I'm not competent enough to fix it, if you could please help it would be appreciated.
PHP Function (Works perfectly).
<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT Name, Role, Salary FROM `users-table`';
mysql_select_db('user_records');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "--------------------------------<br>",
"Name: {$row['Name']} <br> ".
"Role: {$row['Role']} <br> ".
"Salary : {$row['Salary']} <br> ".
"--------------------------------<br>";
}
mysql_close($conn);
?>
This displays the data perfectly! However I'm now trying to include this in a nicely formatted HTML table. (Which is why I'm closing the php tag above).
I'm then trying to use a table like this:
<table >
<tr>
<td>
<?php echo $row['Name'] ?>
</td>
....
It outputs nothing, - I think this problem is caused because I close the first function and then try to reference $row and it doesn't know what to do...?
I think I need to tap in to while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
How can I re-factor this so that I can echo content from the above function to my table?

You didn't write the code you tried, but here is something functional:
$link = mysqli_connect("myhost", "myuser", "mypassw", "mybd");
echo "<table>";
while ($row = mysqli_fetch_array($link, $retval, MYSQL_ASSOC)) {
echo "
<tr>
<td>{$row['Name']}</td>
<td>{$row['Role']}</td>
<td>{$row['Salary']}</td>
</tr>
";
}
echo "</table>";
PS: Since MySQL is deprecated, I replaced your code with MySQLi, and I suggest you do the same :)

As #zessx said, yous should use MySQLi or PDO.
anyway to answer to your question, you have to change the loop in your php code from
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "--------------------------------<br>",
"Name: {$row['Name']} <br> ".
"Role: {$row['Role']} <br> ".
"Salary : {$row['Salary']} <br> ".
"--------------------------------<br>";
}
to
echo '<table>';
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo " <tr>" .
" <td>Name: {$row['Name']}</td>".
" <td>Role: {$row['Role']}</td>".
" <td>Salary : {$row['Salary']}</td>".
" </tr>";
}
echo '</table>';

Related

I want my PHP to create ONE table, but it creates SEVERAL

I need to create a table via php with data from my mysql server. I've managed to establish a connection, and I can create a table, but my problem is that it creates a table for each of the rows, whereas I want one unified. This is my code:
$sql = 'SELECT navn, institution, klip FROM parkeringsdata';
mysqli_select_db($conn , 'parkeringsdb');
$retval = mysqli_query( $conn , $sql );
echo "<br><br><br>";
if(! $retval ) {
die('Could not get data: ' . mysqli_error());
}
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo "<table class='content info'>
<tr>
<td>Navn</td>
<td>Institution</td>
<td>Klip</td>
<td>Rediger</td>
<td>Slet</td>
</tr>
<tr>
<td>".$row["navn"]."</td>
<td>".$row["institution"]."</td>
<td>".$row["klip"]."</td>
<td><button type='button'>Rediger</button></td>
<td><button type='button'>Slet</button></td>
</tr></table><br>";
}
echo "Fetched data successfully\n";
mysqli_close($conn);
EDIT: Thanks for all the quick responses, it's solved now and I see where I made it a rookie mistake. It's for a school assignment and we'd been wracking our brains here :)
You'll want to extract the "", "" and your table-header definition out of the for loop, so it will only be executed once.
And: Creating tables this way is easy to do, but leads to error-prone & difficult to maintain code.
It's okay to learn it step by step.
But most likely you'll want to switch to a templating engine (on client or server side, your&your applications choice) sooner or later.
$table = "<table class='content info'>";
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
$table .= "
<tr>
<td>Navn</td>
<td>Institution</td>
<td>Klip</td>
<td>Rediger</td>
<td>Slet</td>
</tr>
<tr>
<td>".$row["navn"]."</td>
<td>".$row["institution"]."</td>
<td>".$row["klip"]."</td>
<td><button type='button'>Rediger</button></td>
<td><button type='button'>Slet</button></td>
</tr>";
}
$table .= "</table><br>";
You have table start and end tags inside foreach loop.
Echo table outside the while loop
$sql = 'SELECT navn, institution, klip FROM parkeringsdata';
mysqli_select_db($conn , 'parkeringsdb');
$retval = mysqli_query( $conn , $sql );
echo "<br><br><br>";
if(! $retval ) {
die('Could not get data: ' . mysqli_error());
}
echo "<table class='content info'>";
while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
echo "<tr>
<td>Navn</td>
<td>Institution</td>
<td>Klip</td>
<td>Rediger</td>
<td>Slet</td>
</tr>
<tr>
<td>".$row["navn"]."</td>
<td>".$row["institution"]."</td>
<td>".$row["klip"]."</td>
<td><button type='button'>Rediger</button></td>
<td><button type='button'>Slet</button></td>
</tr>";
}
echo "</table><br>";
echo "Fetched data successfully\n";
mysqli_close($conn);

learning how to read data from MYSQL

I'm trying to learn php and mysql, I was trying to read data from my database where i was following something online and encounter an error(s) here is my code
<?php
include 'includes/conn.php';
$query =sprintf("Select * from customer");
$result = mysql_query($query);
if (!$result)
{
$message ='from you see this then it's not connecting!'.mysql_error() ."\n";
$message .= 'everything' .$query;
die($message);
}
while ($customer = mysql_fetch_assoc($result))
{
echo $row['cust_id'];
echo $row['fname'];
echo $row['lname'];
echo $row['gender'];
echo $row['dob'];
}
mysql_free_result($result);
?>
//this is where i was trying to make a connection with the database
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db ='telmar_php';
$con = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db);
?>
Replace
$message ='from you see this then it's not connecting!'.mysql_error() ."\n";
here your string is single quotation marks in it's is causing the problem
with
$message ="from you see this then it's not connecting!".mysql_error() ."\n";
...and to display your results change this:
while ($customer = mysql_fetch_assoc($result))
to this:
while ($row = mysql_fetch_assoc($result))
Please review the below example for reading data my mysql using php.
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}

How to put my data from a table using PHP/MySQL

I know this question has been asked multiple times but looking through and trying the solutions has not got me far.
I would like the table to have a format of:
First name | Last Name
Mike Hannover
Steve Dortmund
however I am not sure how to achieve this, it currently lays out like as I have taken the table coding out that I have tried.
FirstName: Mike - LastName: Hannover
FirstName: Steven - LastName: Dortmund
I have attached my PHP code below and thanks in advance for your time and help.
<body>
<h1>Clients information</h1>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "lastgo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT FirstName, LastName FROM info";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "FirstName: " . $row["FirstName"]. "
- LastName: " . $row["LastName"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Probably the easier way is to build your table is to do it as a table.
// Just looking at this part of the code.
if ($result->num_rows > 0) {
// Begin a table
echo "<table>";
// Create a header row
echo "<tr><th>First Name</th><th>Last Name</th></tr>";
while($row = $result->fetch_assoc()) {
// output data for each row
echo "<tr><td>" . $row["FirstName"]. "</td><td>" .
$row["LastName"]. "</td></tr>";
}
// Close table
echo "</table>";
}
As far I understand you want to print your FirstnName and LastName like so
Change your while loop to:
echo "<table>";
echo "<th>FirstName: </th><th>LastName</th>";
while($row = $result->fetch_assoc()) {
echo "<tr>".
"<td>" .$row["FirstName"] ."</td>"
."<td>" . $row["LastName"]."</td>
.</tr>>";
}
echo "</table>";
you can use a table, then style it the way you want the records to appear
<table>
<tr>
<td>Name</td>
<td>Last Name</td>
</tr>
<?php foreach ($names as $value) : ?>
<tr><td><?php echo $value['Name']; ?></td><td><?php echo $value['LastName']; ?></td></tr>
<?php endforeach; ?>
</table>

Query MySQL on PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Hello everyone i have some question about query on mysql.
I have some code like this
SELECT site.id, site.name_site, site.id_site,site.id_mast,site.address,site.types,
site.longtitude,site.latitude,site.altitude, site.id_region as site,
region.name_region, region.id_region as region
FROM site as site
INNER JOIN region as region
ON site.id_region = region.id_region ORDER BY name_site limit 3;
And also this work:
SELECT * FROM site, region WHERE site.id_region= region.id_region LIMIT 2;
On browser nothing happen, byt on mysql this work, but not on PHP. Why i have some mistake on script php or have problem with query mysql?
Please help me.
Thanks for all hints.
<?php
$dbhost = '............';
$dbuser = '........';
$dbpass = '.......';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = ("SELECT * FROM site, region WHERE site.id_region= region.id_region LIMIT 2;");
mysql_select_db('db_site', $conn) or die ('Invalid query: ' . mysql_error());
?>
<h4><center>Title</center></h4>
<table border='2' cellspacing='0' cellpadding='0'>
<tr>
<td>id</td>
<td>id_site</td>
<td>id_mast</td>
<td>name_site</td>
<td>address</td>
<td>types</td>
<td>longtitude</td>
<td>latitude</td>
<td>altitude</td>
<td>id_region</td>
</tr>
<?php
$retval = mysql_query( $sql, $conn ) or die ('Error did not connection'. mysql_error());
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
print "<tr>";
print "<td>{$row['id']}</td>";
print "<td>{$row['id_site']}</td>";
print "<td>{$row['id_mast']}</td>";
print "<td>{$row['name_site']}</td>";
print "<td style='width:100;'>{$row['address']}</td>";
print "<td style='width:100;'>{$row['types']}</td>";
print "<td>{$row['longtitude']}</td>";
print "<td>{$row['latitude']}</td>";
print "<td>{$row['altitude']}</td>";
print "<td>{$row['id_region']}</td>";
print "</tr>";
}
print "</table>";
mysql_close($conn);
?>
Thanks for all hints. Thanks
try to remove the simple quotes in your printf: $row['id_region'] becames $row[id_region] but I suggest you this to be sure:
echo '<td>'.$row['id_region'].'</td>';
Also, please consider using mysqli instead of mysql, as it's deprecated
<?php
$dbhost = '............';
$dbuser = '........';
$dbpass = '.......';
$dbname = 'db_site';
$my = new Mysqli($dbhost, $dbuser, $dbpass, $dbname);
?>
<h4><center>Title</center></h4>
<table border='2' cellspacing='0' cellpadding='0'>
<tr>
<td>id</td>
<td>id_site</td>
<td>id_mast</td>
<td>name_site</td>
<td>address</td>
<td>types</td>
<td>longtitude</td>
<td>latitude</td>
<td>altitude</td>
<td>id_region</td>
</tr>
<?php
// create a db connexion
$sql = 'SELECT * FROM site, region WHERE site.id_region= region.id_region LIMIT 2;';
// make the query
$stmt = $my->query($sql);
// fetch the results, display them as you want
while($row = $stmt->fetch_assoc())
{
echo '<tr>';
echo '<td>'.$row['id'].'</td>';
echo '<td>'.$row['id_site'].'</td>';
echo '<td>'.$row['id_mast'].'</td>';
echo '<td>'.$row['name_site'].'</td>';
echo '<td style="width:100;">'.$row['address'].'</td>';
echo '<td style="width:100;">'.$row['types'].'</td>';
echo '<td>'.$row['longtitude'].'</td>';
echo '<td>'.$row['latitude'].'</td>';
echo '<td>'.$row['altitude'].'</td>';
echo '<td>'.$row['id_region'].'</td>';
echo '</tr>';
}
echo '</table>';

Fetch information from mysql db using php

Updated script with proper field names. Why isnt this working?
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bookorama", $con);
$sql="SELECT * FROM customers";
$result = mysql_query($sql); // You actually have to execute the $sql with mysql_query();
echo "<table>"; //start the table
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results
{
//echo each row of the table
echo "<tr>
<td>$row['customerID']</td>
<td>$row['name']</td>
<td>$row['Aaddress']</td>
<td>$row['city']</td>
</tr>";
}
echo '</table>'; //close out the table
?>
<?php
$con = mysql_connect("localhost","root","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bookorama", $con);
$sql="SELECT * FROM customers";
$result = mysql_query($sql); // You actually have to execute the $sql with mysql_query();
echo "<table>"; //start the table
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) //Loop through the results
{
//echo each row of the table
echo "<tr>";
echo "<td>$row['CustomerID']</td>";
echo "<td>$row['address']</td>";
echo "<td>$row['city']</td>";
echo "</tr>";
}
echo '</table>'; //close out the table
?>
You can mysql_fetch_array or mysql_fetch_assoc to retriever the rows from you query.
For example using mysql_fetch_array:
$result = mysql_query($sql);
echo "<table><tbody>";
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<tr><td>".$row[0] . "</td><td>" . $row[1] . "</td></tr>";
}
echo "</tbody></table>"
You need to run the query and loop through the results.
You are better off learning from day one about PDO.
And also don't interpolate directly from any user submitted variables (that includes $_POST).
Pretty sure you need to do this when embedding anything more complex than scalars inside double quotes
echo "<tr>
<td>{$row['CustomerID']}</td>
<td>{$row['address']}</td>
<td>{$row['city']}</td>
</tr>";
So whenever you have a more complex var name than "test $var" in quotes, wrap with {} - and even then, it's good practice to wrap scalars too like "test {$var}"

Categories