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]);
Related
I'm creating a webpage that lists ten characters in a game based on their experience levels and displays them with a picture associated each character. My code works, but the output is in a column when I'd like it to be in a row. I did see where something very similar had been asked here: MySQL data from database align horizontally and I tried to follow that example but either ended up with errors or the faces didn't appear. I'm a hobbyist, I'm just doing this for friends, so my knowledge is pretty basic.
Relevant code:
<table border="3" width="90%">
<tr>
<th width="25%">XP</th>
<td>
<?php
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<left>";
echo "<table border='1'>";
echo "<tr><td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td></tr>";
echo "</table>";
echo "<br>";
}
?>
</td>
</tr>
</table>
Anyone got any suggestions? Thanks!
So after following Bombelman's suggestion below, I got it to work. In case anyone else runs into this problem, here is the working code:
<tr>
<th width="25%">Goody Two Shoes</th>
<td><?php
echo "<table border='1'><tr>";
echo "<left>";
$resultgood = mysqli_query($con,"SELECT * FROM Life WHERE goodxp > 0 ORDER BY goodxp DESC LIMIT 10");
while($row = mysqli_fetch_array($resultgood))
{
$face = mysqli_query($con,"SELECT face FROM Description WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($face);
$face = $row[0];
$name = mysqli_query($con,"SELECT charname FROM Life WHERE charname='$row[charname]'");
$row = mysqli_fetch_row($name);
$name = $row[0];
echo "<td>";
echo "<img src='pictures/$face' alt='$name' border='2'>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
?></td>
</tr>
place the "table" and "row" tag out of the loop, and have the results in between the "td" tags looped only.
Looking at your script, you have several tables.
Make sure only the < td > and < /td > tags are within the while-loop.
The output should be similar to my example.
Hope it helps !
<table style="width:100%">
<tr>
<td>Character 1</td>
<td>Character 2</td>
<td>Character 3</td>
<td>Character 4</td>
<td>Character 5</td>
</tr>
</table>
Looking at the sql queries makes me think you ought to be able to do a basic join upon the two tables rather than having nested queries within a loop. The generation of the html table should be fairly straightforward - iterate through the recordset results for rows in the table and iterate through the fields returned by the query for individual cells within the table row.
$sql='select l.*, d.face from `life` l
join `description` d on d.`charname`=l.`charname`
where l.`goodxp` > 0
order by l.`goodxp` desc
limit 10';
$res=$con->query( $sql );
/* fetch the column names into an array */
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
$html=array();
$html[]='<table>';
/* add field names as column headers */
$html[]='<tr>';
foreach( $fields as $field )$html[]='<th>'.$field.'</th>';
$html[]='</tr>';
/*
iterate through recordset,
add new row for every record
but table cell for every
field in record
*/
while( $rs=$res->fetch_object() ){
$html[]='<tr>';
foreach( $fields as $field ){/* show image or text */
$data = $field=='face' ? "<img src='pictures/{$rs->$field}' />" : $rs->$field;
$html[]='<td>'.$data.'</td>';
}
$html[]='</tr>';
}
$html[]='</table>';
/* render table */
echo implode( PHP_EOL, $html );
Depending upon the version of PHP you may get nagged at when using the array_walk function and passing the third argument by reference. If that is the case then change
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key, $fields ){
$fields[]=$item->name;
},&$fields );
for
$fields=array();
array_walk( $res->fetch_fields(),function( $item, $key ){
global $fields;
$fields[]=$item->name;
} );
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).
I'm trying to place the output of this PHP SQL query into a database table, but it is outputting all of the row data into one column.
if(isset($_POST['submit'])) {
$name = htmlentities($_POST['name']);
$parts = explode(" ", $name);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
$connection = mysql_connect("localhost", "user", "password");
mysql_select_db("shoretoshore", $connection);
$result = mysql_query("SELECT ship_no, shipment_id, arrival_date, origin, destination, lname, fname from shipment, captain WHERE captain.capt_id=shipment.capt_id AND captain.fname='$firstname' AND captain.lname='$lastname'", $connection);
echo '<table border="0" cellpadding="5px" cellspacing="1px" style="font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#E1E1E1" width="100%">
<tr bgcolor="#FFFFFF" style="font-weight:bold">
<th>Shipment No.</th>
<th>Shipment Id.</th>
<th>Arrival Date</th>
<th>Origin</th>
<th>Destination</th>
<th>Last Name</th>
<th>First Name</th>
</tr>';
while ($row = mysql_fetch_row($result)) {
foreach ($row as $value)
print "<tr><td>"."{$value}"."</td></tr>";
echo "<br>";
}
echo "</table>";
}
How do I output the results of the query into an HTML table?
You are putting the $value inside quotation marks, it will be treated as string.
Try:
while ($row = mysql_fetch_row($result)) {
echo '<tr>';
foreach ($row as $value)
{
echo "<td>".$value."</td>";
}
echo "</tr>";
}
You need to explain the issue you're having. But from what I can see off the bat, you're looping through all the values of the row and outputting them as rows itself, instead of as a cell within the table row. The curly brackets around value are unnecessary as well, since you are concatenating the strings, you can just do '<tr><td>'.$value.'</td></tr>' OR "<tr><td>$value</td></tr>". PHP will parse variables within a string if the string is double quoted. I would also refrain from adding <br> tags as direct children of a table. If you need spacing between table rows, use padding and margins.
try this
while ($row = mysql_fetch_row($result)) {
print "<tr><td>".$row[0]."</td></tr>";
echo "<br>";
}
The problem is that you're outputting a <tr> tag for every row and column. You need to move the <tr> outside the inner loop.
Technically, you don't need to concatenate "{$value}" with the other two strings, but you really should pass $value through htmlspecialchars() to avoid producing incorrect HTML if the value contains any < or & characters. Eg:
while ($row = mysql_fetch_row($result)) {
print '<tr>';
foreach ($row as $value) {
$v = htmlspecialchars ($value);
print "<td>$v</td>";
}
echo "</tr>\n";
}
Also, you're not supposed to have a <br> element between table rows, which is why I replaced it with a newline above. Personally, I would skip the closing </td> and </tr> tags since they are optional in HTML.
Note also, that the MySQL extension is deprecated and no longer maintained. You should be using MySQLi or PDO these days.
while ($row = mysql_fetch_row($result)) {
echo '<tr>';
foreach ($row as $value)
{
echo "<td>".$value."</td>";
}
echo "</tr>";
}
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)
First, I really hope I don't get beat down for asking this, but I'm willing to risk it in order to be pointed in the right direction so I can learn.
I have a .php script, and inside my PHP script I have written the code to connect to MySQL database.
Here's the question:
I have a table that will be used for a very simple display of food items. Currently I have:
<table width="1024" border="0" cellpadding="10" cellspacing="5" align="center">
<tr>
<td colspan="2"><font>Item Name</font></td>
<td colspan="2"><font>Item Name</font></td>
<td colspan="2"><font>Item Name</font></td>
</tr>
and it keeps going with other table row elements...
WHERE IT SAYS "ITEM NAME," HOW DO I INPUT CODE TO PULL DATABASE INFORMATION. The database name I have is "TEST" and I'd like each item name to list a different item from the "ITEM" table.
ANY HELP WOULD TRULY BE APPRECIATED.
You really need to do more research on this. Here is an example of Php code that pulls data from database courtesy of w3 schools. See here http://www.w3schools.com/php/php_mysql_select.asp.
<?php
$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 Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
You have to iterate over the results from the database, otherwise you'll have access only to the first row (or where the array pointer is).
Your question is the basics of programming, and there are million of resources on this topic around the web. I'll just give you a small sample code, and from here you can start debugging and modifying to your taste.
//Connect to MySQL Database
$connection = mysql_connect('host', 'user', 'password') or die("Connection error. Details: ".mysql_error());
//Select the database
$db_select = mysql_select_db('dbname', $connection);
//Create the query
$query = mysql_query("SELECT * FROM `foods`") or die("Error in query. Details: ".mysql_error());
//Check if the query has results, and iterate over it
if (mysql_num_rows($query) > 0)
{
//Creates the table
echo '<table>';
//Iterate over the MySQL results and print the data
while ($result = mysql_fetch_assoc($query))
{
echo '
<tr>
<td>'.$result['item_name'].'</td>
</tr>
';
}
echo '</table>';
}
else
{
echo "Your query hasn't returned results";
}
Try this and don't forget to change the mysql host name, username, password, db name and table name.
Regards.
try this:
$conn = mysql_connect('host', 'user', 'password') or die("Connection error. Details:".mysql_error());
$db_select = mysql_select_db('<your_db_name', $conn);
$sql = mysql_query("SELECT * FROM `foods`")
if($sql)
{
echo '<table>';
while ($result = mysql_fetch_assoc($query))
{
echo '<tr><td>'.$result['<field_name1>'].'</td>';
echo '<td>'.$result['<field_name2>'].'</td>';
.....
.....
echo '</tr>';
}
echo '</table>';
}
else
{
echo "no results is there";
}
note: you should know your table column name , provide the same name in field_names
you can print any number of columns present in your table.
thanks