Inserting html table data with php & mysql - php

I'm trying to display data from a MySQL table in a html table using php, I've looked at a few tutorials online including answers on StackOverflow... I've implemented it the way said tutorials have described but I am getting no output.
<table border="1px solid black" cellpadding="0px" cellspacing="0px" width="100%">
<thead>
<tr>
<th>Date</th>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
<th>Thursday</th>
<th>Friday</th>
<th>Saturday</th>
<th>Sunday</th>
</tr>
</thead>
<?php
include('dbConnect.php');
$sql = "SELECT * FROM nurses";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['idno'] . "</td>";
echo "<td>" . $row['surname'] . "</td>";
echo "</tr>";
}
?>
</table>
I know that my db connection is successful as I test for this. All that's getting output is the <thead> and then nothing. I don't understand why this isn't working :/

If you say you have tested this, then there should be no error when trying to execute mysql_query. To be sure that any data is being fetched though, please do a var_dump(mysql_fetch_assoc($result)) after the $result = mysql_query($sql); line to see if at least a single line is being returned from the database. Additionally, you should not use mysql_* functions anymore since they are being deprecated.
Check here how it works. http://php.net/manual/en/function.mysql-query.php
In the case that var_dump returns at least a single result, then most likely $row['idno'] is not a proper column name in your results (you can see what is in the array from the var_dump)

Related

PHP List Users from SQL Database in Table

Hi so im trying to put all of the useres in a database, table into a html table this is what i have:
<table class="table table-striped">
<thead>
<tr>
<th>UUID</th>
<th>Full Name</th>
<th>Email</th>
<th>Access Key</th>
<th>Phone Number</th>
<th>Activated</th>
<th>Role</th>
</tr>
</thead>
<tbody>
<?php
include_once('inc/conf/databaseConnect.php');
$query = mysql_query("SELECT * FROM list_users ORDER by id");
while($row = mysql_fetch_array($query)){
echo "<tr>";
echo "<td>".$row['uuid']."</td>";
echo "<td>".$row['firstname'].$rowtwo['lastname']."</td>";
echo "<td>".$row['email']."</td>";
echo "<td>".$row['security_key']."</td>";
echo "<td>".$row['phone_no']."</td>";
echo "<td>".$row['activated']."</td>";
echo "<td>".$row['role']."</td>";
echo "</tr>";
}
?>
</tbody>
</table>
This dosnt return anything, or any errors. It connects to the database correctly ive checked that its just not retrieving the users.
Image of database structure
databaseConnect.php:
<?php
//Create Connnection
$sqlLink = mysqli_connect('localhost', 'root', 'classified', 'user_details');
//If Error Connecting
if(!$sqlLink) {
die('<center><br><h3>Error connecting to servers Database.');
}
?>
After seeing your edit because you did not originally show us which connection method you were using; the almighty answer here (least the most important one) is that you can't mix different MySQL APIs.
Can I mix MySQL APIs in PHP?
You need to use the same one from connection to query.
Plus that $rowtwo should be $row as I stated in comments along with my asking about what was inside your databaseConnect.php file.
Get to work with prepared statements also to help protect against an SQL injection.
https://en.wikipedia.org/wiki/Prepared_statement
Thanks. I have fixed the issue i updated to using mysqli's methods
<?php
include_once('inc/conf/databaseConnect.php');
$query = $sqlLink->query("SELECT * FROM list_users ORDER by id");
while($row = $query->fetch_array()){
echo "<tr>";
echo "<td>".$row['uuid']."</td>";
echo "<td>".$row['firstname'].$row['lastname']."</td>";
echo "<td>".$row['email']."</td>";
echo "<td>".$row['security_key']."</td>";
echo "<td>".$row['phone_no']."</td>";
echo "<td>".$row['activated']."</td>";
echo "<td>".$row['role']."</td>";
echo "</tr>";
}
?>
At least check for errors:
if ($query = mysql_query("SELECT * FROM list_users ORDER by id");) {
...
} else {
echo '<b>MySQL error:</b><br>' . mysql_error() . '<br />';
}
You must use mysql_fetch_assoc() instead of mysql_fetch_array or fetch like this mysql_fetch_array($result, MYSQL_ASSOC).

PHP mysql_fetch_array/Row not displaying Unique elements

I am trying to create a php based search function, with following code:
<?php
$d_name=$_POST['id'];
//connect to the database
$db=mysql_connect ("localhost", "root", "") or die ('I cannot connect to the database because: ' . mysql_error());
//-select the database to use
$mydb=mysql_select_db("pgr");
if(!$mydb)
echo "db not selected";
//-query the database table
$d_name=(int)$d_name;
$sql="SELECT * FROM omimentry WHERE OMIM_ID=$d_name";
//-run the query against the mysql query function
$result=mysql_query($sql) or die(mysql_error());
$n=mysql_fetch_array($result);
//-create while loop and loop through result set
if($n)
{
echo "<table border = 1 width=\"95%\" border=\"0\" cellpadding=\"2\" cellspacing=\"2\" class=\"text_black\">
<tr class=\"yellow\">
<td width=\"10%\" align=\"center\" valign=\"middle\" class=\"text_black_bold\">OMIM_ID</td>
<td width=\"20%\" align=\"center\" valign=\"middle\" class=\"text_black_bold\">location(chromosome)</td>
<td width=\"30%\" align=\"center\" valign=\"middle\" class=\"text_black_bold\">phenotype</td>
<td width=\"20%\" align=\"center\" valign=\"middle\" class=\"text_black_bold\">MIMnumber</td>
<td width=\"20%\" align=\"center\" valign=\"middle\" class=\"text_black_bold\">Gene</td>
<td width=\"20%\" align=\"center\" valign=\"middle\" class=\"text_black_bold\">GeneMIMnumber</td>
<td width=\"20%\" align=\"center\" valign=\"middle\" class=\"text_black_bold\">geneid</td>
<td width=\"30%\" align=\"center\" valign=\"middle\" class=\"text_black_bold\">protein</td>
</tr> ";
while($rows=mysql_fetch_row($result))
{
echo "
<tr class=\"text_black\" align=\"left\" valign=\"middle\">
<td width=\"10%\">$rows[1]</td>
<td width=\"20%\">$rows[2]</td>
<td width=\"30%\">$rows[3]</td>
<td width=\"10%\">$rows[4]</td>
<td width=\"20%\">$rows[5]</td>
<td width=\"20%\">$rows[6]</td>
<td width=\"20%\">$rows[7]</td>
<td width=\"30%\">$rows[8]</td>
</tr>";
}
echo " </table> " ;
}
else
echo "Sorry Data Not Available";
?>
The problem, which is rather unique, is that this code is displaying those queries which have duplicate entries(and even for those, it is displaying result for the last row, not all rows with duplicate OMIM_ID). And for unique OMIM_ID, there are no results, even though there is no explicit error.
Table Scheme:
int OMIM_ID
varchar2 location(chromosome)
varchar2 phenotype
int MIMnumber
varchar2 Gene
int geneMIMNumber
int geneid
varchar2 Protein
Any clues on what I am doing wrong ?
--Update--
Even after updating my code to:
<?php
$d_name=$_POST['id'];
$db = new PDO('mysql:host=localhost;dbname=pgr;charset=utf8', 'root', '');
if(!$mydb)
echo "db not selected";
//-query the database table
$d_name=(int)$d_name;
$stmt = $db->prepare("SELECT * FROM table WHERE id=?");
$stmt->execute(array($d_name));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "<br>";
echo "<br>";
foreach($rows as $name => $value) {
echo "<tr><th>".htmlspecialchars($name).
"</th><td>".htmlspecialchars($value)."</th></tr>";
?>
I am getting same error.
Update: A more clear view on problem.
Database:
Table:
int OMIM_ID|varchar2 location(chromosome)|varchar2 phenotype|int MIMnumber|varchar2 Gene|int geneMIMNumber|int geneid|varchar2 Protein
Entries:
2141|24q.xx|Some disease|4651|SomeID|56525|5625|SomeProteinID
2141|21q.xx|Some disease|4651|SomeID|56545|5625|SomeProteinID
2142|24q.xx|Some disease|4651|SomeID|56525|5625|SomeProteinID
Now, given 2141 as query, the code will display 2nd entry in result, not the first one, which should have been included too.
If 2142 is the query, there is no output, ideally, the possible output should have been the row described by OMIM_ID 2142.
I do not know what is in your tables and what duplicates you are referring to. Because you got trashed so bad, I risked getting trashed helping you with unconventional code.
The comments about using depreciated mysql had no bearing on your code but they just don't like others that come here for a solution to think it is OK to use mysql. They do not realize when you post a question how frustrated you are and how they are adding to your frustration. They mean well but in your case you changed your code to accommodate them and you not realizing it had nothing to do with a solution.
NOTE: this solution uses depreciated mysql and not the newer mysqli
This will eliminate duplicates:
while ($row = mysql_fetch_array($results, MYSQL_NUM)) {
$data[] = serialize(array($row[1],$row[2],$row[3],$row[4],$row[5]));
}
$data = array_unique($data);
To try and keep the first duplicate:
while ($row = mysql_fetch_array($results, MYSQL_NUM)) {
$data[] = serialize(array($row[1],$row[2],$row[3],$row[4],$row[5]));
}
$data = array_reverse ($data);
$data = array_unique($data);
ksort($data); // puts them back in original order.
OR
while ($row = mysql_fetch_array($results, MYSQL_NUM)) {
$columns = serialize(array($row[1],$row[2],$row[3],$row[4],$row[5]));
if (!in_array($columns,$data)){
$data[] = serialize(array($row[1],$row[2],$row[3],$row[4],$row[5]));
}
}
Then the new loop is:
foreach($data as $key => $value){
$row = unserialize($value);
}
There are other ways to use this to eliminate some dups and exclude others.
$uniqueRows = serialize(array($row[1],$row[2]));
$data[$uniqueRows] = array($row[3],$row[4],$row[5]);

Search the results from a query

I have a site where members can mark other members as 'a favourite'. User are able to search the members table in various ways and I want to show from any of the results that are returned whether or not the users returned are favourites of the current user.
This is some very simplified code I have been using to try and get this query to work but I just can't figure it out. Whenever I add 'GROUP BY' to avoid duplicate results from my LEFT JOIN the 'if' statement does not work. The 'if' statment does work however, if I omit the 'GROUP BY' but I get all rows from members table and the favourites table. Thanks.
$result = mysqli_query($db_conx, "SELECT members.*, user_favourites.* FROM members LEFT JOIN user_favourites ON members.id = user_favourites.fav_id GROUP BY members.id");
echo "<table border=''>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>A favourite of User</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
if ($visitor == $userid ){
$msgs = "x";
}
else { $msgs = "0";
}
echo "<td>". $msgs. "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I suggest to you, tu use 2 query's insted one. Simple query is a fast querys. If your site scale up, your query will be slow query and it cause performance problems.
Idea:
For one hand: SELECT FROM members, get all and put it inside array, key=member.id
$members[$row['member_id']]=$row;
On the other hand: SELECT * FROM user_favourites, and put it inside the previous array, refereced by the key fav_id use distinc if you have duplicates.
$members[$row['fav_id']]['favourites']=$row;
Perfect now you have all you need, an array with all information, iterate it.
JilianJ something like this:
<?
//Prepare
$all_users=array()
$query_users='SELECT * from user';
$query_favourites='SELECT * FROM user_favourites';
//Now I find all members information
$users=mysqli_query($db_conx,$query_users);
while($user = mysqli_fetch_array($users)) {
$all_users[$user['id']]=$user;
}
//Now I add favourite information to the users information
$favourites=mysqli_query($db_conx,$query_favourites);
while($favourite = mysqli_fetch_array($favourites)) {
$all_users[$favourite['fav_id']]['fovourite'][]=$favourite['fav_id'];
}
?>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
<th>A favourite of User</th>
</tr>
<? foreach ($information as $key=>$item) {?>
<tr>
<td><?=$item['firstname'];?></td>
<td><?=$row['lname'];?></td>
<td><?=$row['email'];?></td>
<td>
<? foreach($item['favourites'] as $key2=>$item2) { ?>
<p><?=$all_members[$item2]['name];?></p>
<? } ?>
</td>
</tr>
<? } ?>
</table>
Good luck

Create multiple tables by cycling through a query

Here is my current code:
$varVeh=$_POST['Veh_num'];
$sql_HiScores = "SELECT
c.course_name as course,
e.distance as distance, e.score as score,
e.time as time, e.user as User
FROM hc_entries e
LEFT JOIN hc_course c on e.course=c.course_num
WHERE e.vehicle=$varVeh
ORDER BY course, score DESC";
$result_HiScores = mysql_query($sql_HiScores);
$sql_vehName="SELECT Veh_name FROM hc_vehicle_type WHERE Veh_num=$varVeh ";
$result_vehName = mysql_query($sql_vehName);
$vehName=mysql_fetch_assoc($result_vehName);
echo "<table><tr><th>Best Scores for ".$vehName['Veh_name']."</th></tr></table>";
echo "<table border='1'>";
echo "<tr><th>Course</th><th>Score</th><th>Distance</th><th>Player</th><th>Time</th></tr>";
while($row = mysql_fetch_array($result_HiScores))
{
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
echo "<td>" .$row['User'] . "</td>";
}
echo "</table>";
What I think I have to do is create a query that selects * from e.course that builds an array. Then cycle through the existing query with the array results. Finally, I would like to display individual tables for each course and limit it to the top 5 results for each course.
Can anyone confirm or deny my logic, and point me in a direction?
First of all, you shouldn't be using the mysql_ functions, they're deprecated. At the least, you should switch to mysqli_ (a pretty easy switch), or better, learn how to use PDO. It's a bit different and more involved to switch, but your code will be better and safer for it.
With that out of the way: your logic is pretty accurate. Limiting your results to the top 5 results for each course in one query isn't something that's easily done with SQL to my knowledge, so your plan is good: query a list of courses, then cycle through them with your existing query, running it once for each course, with a LIMIT 5 to get the top 5.
You might as well keep the table generation within this loop as well, since it's a table-per-course. You'd want to move the VehName query out of the loop, since you only need to run that once.
Also, some unsolicited PHP advice: any text outside of the tags will just be output directly, so take advantage of its built-in-templating and alternative syntax to make your table generation code nicer:
<?php
/* Gather your data here... */
?>
<table>
<tr><th>Best Scores for <?php echo $vehName['Veh_name'] ?></th></tr>
</table>
<table border='1'>
<tr>
<th>Course</th>
<th>Score</th>
<th>Distance</th>
<th>Player</th>
<th>Time</th>
</tr>
<?php while($row = mysql_fetch_array($result_HiScores)): ?>
<tr>
<td><?php echo $row['course'] ?></td>
<td><?php echo $row['score'] ?></td>";
<td><?php echo $row['distance'] ?></td>";
<td><?php echo $row['User'] ?></td>";
</tr>
<?php endwhile; ?>
</table>
put the entire table html inside the while loop and add 'LIMIT 5' to the end of your query

Display SQL Table in PHP

I am trying to display a table in php. I have established a valid connection. I get the error:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /Applications/XAMPP/xamppfiles/htdocs/project.php on line 17
The page's code:
<html>
<head>
<title>PHP Site Michael Mazur</title>
</head>
<body>
<?php
//connect to DB
$con=mysql_connect("localhost","mike","mike");
$db_found = mysql_select_db("my_guitar_shop2");
$result = mysql_query("SELECT firstName,lastName FROM customers");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['firstName'] . "</td>";
echo "<td>" . $row['lastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
The rest of your while loop could look like this
while($row = mysql_fetch_array($result)){
print "<tr><td>".$row['Firstname']."</td><td>".$row['Lastname']."</td></tr>";
}
print "</table>";
Try putting these lines on a single line as i have done above.
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
like
echo "<table border='1'><tr><th>Firstname</th><th>Lastname</th></tr>";
Other useful options here.
http://php.net/manual/en/function.mysql-fetch-array.php
http://php.net/manual/en/control-structures.foreach.php
Given that part of the page's code is missing, this is only a guess. But it looks like part of your problem is that you've double-selected the database (a no-no).
Also, the while statement looks slightly suspect (no opening brace to verify context).
Additionally, if you are going to pass $con to the database selector, you should also pass it to the mysql_query calls (good practice for readability).

Categories