Fetch from mySQL to HTML TABLE - php

I have used this code but its not fetching anything other than displaying the table on the web.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>database connections</title>
</head>
<body>
<?php
$username = "root";
$password = " ";
$host = "localhost";
$connector = mysql_connect($host,$username,$password)
or die("Unable to connect");
echo "Connections are made successfully::";
$selected = mysql_select_db("ticad", $connector)
or die("Unable to connect");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM users ");
?>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<thead>
<tr>
<th>id</th>
<th>Names</th>
<th>Company</th>
<th>Position</th>
<th>Email</th>
<th>Event</th>
<th>Comments</th>
</tr>
</thead>
<tbody>
<?php
while( $row = mysql_fetch_assoc( $result ) ){
echo
"<tr>
<td>{$row\['id'\]}</td>
<td>{$row\['Names'\]}</td>
<td>{$row\['Company'\]}</td>
<td>{$row\['Position'\]}</td>
<td>{$row\['Email'\]}</td>
<td>{$row\['Event'\]}</td>
<td>{$row\['Comments'\]}</td>
</tr>\n";
}
?>
</tbody>
</table>
<?php mysql_close($connector); ?>
</body>
</html>
This is my Table and dabase
This is what am getting when I run the code as a web. I want all the records to be displayed on the table as we fetch from the table users

try this and don't escape... And as I saw your picture. You need to upload your file onto webserver with support of PHP. Rename your file to .php extension
echo
"<tr>
<td>".$row['id']."</td>
<td>".$row['Names']."</td>
<td>".$row['Company']."</td>
<td>".$row['Position']."</td>
<td>".$row['Email']."</td>
<td>".$row['Event']."</td>
<td>".$row['Comments']."</td>
</tr>\n";

Don't escape the brackets:
<td>{$row['id']}</td>

Related

index of fetch array

i want to get the index of td that the user clicked , i have an html table fill from database using php ...
this is my index.php :
<html>
<head>
<title>Last 10 Results</title>
</head>
<body>
<table>
<thead>
</thead>
<tbody>
<tr>
<?php
session_start();
$connect = mysqli_connect("localhost","root","","test");
if (!$connect) {
die(mysql_error());
}
$results = mysqli_query($connect,"SELECT * FROM family where parent_id = 0");
while($row = mysqli_fetch_assoc($results)) {
?>
<td onclick="window.location='index2.php'"
<?php $id = $row['id'];
$_SESSION['varname'] = $id;?>>
<?php echo $row['name']?> <br/>
<?php echo $row['description']?> <br/>
<?php echo $row['parent_id']?> <br/>
</td>
<?php
}
?>
</tr>
</tbody>
</table>
</body>
</html>
this is my index2.php :
<html>
<head>
<title>Last 10 Results</title>
</head>
<body>
<table>
<thead>
</thead>
<tbody>
<tr>
<?php
session_start();
$gg = $_SESSION['varname'];
echo $gg;
$connect = mysqli_connect("localhost","root", "","test");
if (!$connect) {
die(mysql_error());
}
$results = mysqli_query($connect,"SELECT * FROM family where parent_id = '$gg' ");
while($row = mysqli_fetch_array($results)) {
?>
<td>
<?php echo $row['id']?> <br/>
<?php echo $row['name']?> <br/>
<?php echo $row['description']?> <br/>
<?php echo $row['parent_id']?> <br/>
</td>
<?php
}
?>
</tr>
</tbody>
</table>
</body>
</html>
now i want to take the "id" of the td that the user click on,, but this code always give me the last id in my database ...
what can i do ?
Replace in Index.php:
<td onclick="window.location='index2.php'"
With:
<td onclick="window.location='index2.php?parent_id=<?php echo $row['id']; ?>'"
And in
Index2.php:
$gg = $_SESSION['varname'];
With:
$gg = (int)$_GET['parent_id'];
It's better to use $_GET variable for this than $_session (urls are search engine friendly)

Php database not able to be retrieved

I have a problem of data not being retrieved from database. It only echos the sentence that I typed instead of the data in my database. I've tried it for several times and it still does not work. Is there anything wrong with my code? Please help
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>database connections</title>
</head>
<body>
<?php
$username = "database-username";
$password = "database-password";
$host = "localhost";
$connector = mysqli_connect($host,$username,$password)
or die("Unable to connect");
echo "Connections are made successfully::";
$selected = mysqli_select_db($connector, "test_db")
or die("Unable to connect");
//execute the SQL query and return records
$result = mysqli_query("SELECT * FROM table_one ");
?>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<thead>
<tr>
<th>Employee_id</th>
<th>Employee_Name</th>
<th>Employee_dob</th>
<th>Employee_Adress</th>
<th>Employee_dept</th>
<td>Employee_salary</td>
</tr>
</thead>
<tbody>
<?php
while( $row = mysqli_fetch_assoc( $result ) ){
echo
"<tr>
<td>{$row\['employee_id'\]}</td>
<td>{$row\['employee_name'\]}</td>
<td>{$row\['employee_dob'\]}</td>
<td>{$row\['employee_addr'\]}</td>
<td>{$row\['employee_dept'\]}</td>
<td>{$row\['employee_sal'\]}</td>
</tr>\n";
}
?>
</tbody>
</table>
<?php mysqli_close($connector); ?>
</body>
</html>
You need below Changes in your Code :
1) Change these line :
$result = mysqli_query("SELECT * FROM table_one ");
To below line :
$result = mysqli_query($connector, "SELECT * FROM table_one ");
2) Change these lines :
<td>{$row\['employee_id'\]}</td>
<td>{$row\['employee_name'\]}</td>
<td>{$row\['employee_dob'\]}</td>
<td>{$row\['employee_addr'\]}</td>
<td>{$row\['employee_dept'\]}</td>
<td>{$row\['employee_sal'\]}</td>
To Below Lines :
<td>{$row['employee_id']}</td>
<td>{$row['employee_name']}</td>
<td>{$row['employee_dob']}</td>
<td>{$row['employee_addr']}</td>
<td>{$row['employee_dept']}</td>
<td>{$row['employee_sal']}</td>
That's It.

Get specific data from database with PHP code when a user login

I want to get data from my database with PHP code. In brief when a user log in with id & password i want to show his data only in user panel, but i got some error: Here is my user admin panel code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>User Panel</title>
<link rel="stylesheet" href="assets/demo.css">
<link rel="stylesheet" href="assets/form-labels-on-top.css">
</head>
<body>
<header>
<h1 align="center"><b>User Information Details</b></h1></br>
</header>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "xyz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
include('user_login_check.php');
$result= mysql_query("SELECT * FROM `user_information` WHERE `user_id` = '".$_SESSION['id']."' ")or die(mysql_error());
// $result = mysql_query("SELECT * FROM user_information WHERE user_name='" . $_POST["user_name"] . "' and user_password = '". $_POST["user_password"]."'");
?>
<form>
<table border="5" style= "background-color: #333333; color: #FFF; margin: 0 auto; padding:100px" >
<thead>
<tr>
<th>User ID</th>
<th>User Type</th>
<th>User Name</th>
<th>User Country</th>
<th>User Email</th>
<th>User Phone</th>
<td>User Address</td>
<td>User Password</td>
<td>User Status</td>
<td>Edit</td>
</tr>
</thead>
<tbody>
<?php
while( $row = mysqli_fetch_assoc( $result ) ){
echo
"<tr>
<td>{$row['user_id']}</td>
<td>{$row['user_type']}</td>
<td>{$row['user_name']}</td>
<td>{$row['user_country']}</td>
<td>{$row['user_email']}</td>
<td>{$row['user_phone']}</td>
<td>{$row['user_address']}</td>
<td>{$row['user_password']}</td>
<td>{$row['user_status']}</td>
<td><img src='image/editicon.jpeg'/></td>;
</tr>\n";
}
?>
</tbody>
<div align="left" style="background:#333333">
<h1><input type="button" value="Log Out" onClick="window.location.href='logout_user.php'" /> </h1>
</div>
</table>
</form>
</body>
</html>
problem is in specially this section
$result= mysql_query("SELECT * FROM `user_information` WHERE `user_id` = '".$_SESSION['id']."' ")or die(mysql_error());
here is my login check code:
<?php
//connect the database
$hostName="localhost";
$dbUsername="root";
$dbPassword="";
$dbName="xyz";
mysql_connect($hostName,$dbUsername,$dbPassword) or die("Connection failed");
mysql_select_db($dbName) or die("Database name doesn't exist");
//start session
#session_start();
if(isset($_POST["user_name"] , $_POST["user_password"]))
{
$User_name = $_POST["user_name"];
// echo "$User_name";
$User_password = $_POST["user_password"];
// echo "$User_password";
$sql = "SELECT * FROM `user_information` WHERE `user_name`='".$User_name."' AND `user_password`='".$User_password."' ";
$result = mysql_query($sql) or trigger_error(mysql_error().$sql);
// $result = mysql_query("SELECT * FROM `user_info` WHERE `User_name`='".$username."' AND `User_password``='".$password."'");
$my_arary = array();
while($row = mysql_fetch_assoc($result))
{
$_SESSION['id']= $row["Id"];
// echo $_SESSION['login_user_id'];
$_SESSION['user_password']= $row["user_password"];
//echo $_SESSION['login_user_password'];
$_SESSION['user_name']= $row["user_name"];
//echo $_SESSION['login_user_name'];
$my_arary[] = $row;
print_r($row);
if($User_name == $_SESSION['user_name'] && $User_password == $_SESSION['user_password']){
header("Location: userpanel.php");
//echo "successfully logged in";
}
else{
echo "no matches";
header("Location: user_login_basic.php");
}
}
}
?>
You set your $_SESSION['id']= $row["Id"] . Are you sure there column Id in your table? Because you using user_id instead of Id in your query in user admin panel code

HTML table with sql data in php (table row depend by sql columns)

Hello i got this sample data in sql
$data = array(
array('id' => '1','name' => 'name1','surname' => 'surname1'),
array('id' => '2','name' => 'name2','surname' => 'surname2'),
array('id' => '3','name' => 'name3','surname' => 'surname3'),
array('id' => '4','name' => 'name4','surname' => 'surname4')
);
I want to dispplay in in html table but my code didnt work :
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th align="left" valign="middle">id</th>
<th align="center" valign="middle">name</th>
<th align="center" valign="middle">surname</th>
</tr>
</thead>
<?php
$result = mysql_query($select_data);
while ($data = mysql_fetch_row($result)) {
}
?>
<tbody>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
</tbody>
</table>
</body>
</html>
But i wann't also that the numer of rows in html table depends by number of columns in sql table. For example in this case i want to display only three rows (three columns in sql table). When i add the column's to sql table i want to rows in html output table increses dynamicly.
Could someone help me with this code ?
Change your code to this:
<tbody>
<?php
$result = mysql_query($select_data);
while ($data = mysql_fetch_row($result)) {
?>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
<?php
}
?>
</tbody>
You are closing your while loop before displaying the results
You close your while-loop not correct:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
$result = mysql_query($select_data);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th align="left" valign="middle">id</th>
<th align="center" valign="middle">name</th>
<th align="center" valign="middle">surname</th>
</tr>
</thead>
<tbody>
<?php while ($data = mysql_fetch_row($result)):?>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
<?php endwhile;?>
</tbody>
</table>
</body>
</html>
Using the the "while(cond):" and "endwhile;" command you can see better where something starts and where it ends than using the encapsulation with braces.
Please consider to switch your Database Wrapper from mysql_ to PDO or mysqli, since mysql is not anymore actively supported.
You could also use instead:
<?php echo $data['id']?>
rather the shortform:
<?=$data['id']?>
Which is also avaiable w/o php short open after 5.3 (I think it was 5.3)
If I understand your question correctly, you would like to have the number of returned rows match the number of columns in your table dane. The following code should do just that and I'm using mysqli which I strongly recommend. The mysql_query extension is deprecated as of PHP 5.5.0.
<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table
// Let's make sure we could establish a connection
if($db->connect_errno > 0){
die('Unable to connect to the database ' . $db->connect_error);
}
// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";
if(!$result = $db->query($select_cols)){
die('There was an error running the query.');
}
while($row = $result->fetch_assoc()){
$cols[] = $row['column_name']; // Store the columns to an array. It will be further used.
}
// Implode the column names to a comma delimited string to use in the next select. It's also a good practice not to use asterisk in your select statements
$table_headers = implode(',', $cols);
// Query for records with a limit to number columns in the $table_name
$select_data = "SELECT $table_headers FROM $table_name ORDER BY `id` DESC LIMIT 0 , $result->num_rows";
if(!$result = $db->query($select_data)){
die('There was an error running the query ' . $db->error);
}
while($row = $result->fetch_assoc()){
$data[] = $row; // Store the data into an array to be used in the html table
}
$db->close(); // Close our connection
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<?php foreach ($cols as $k) : // Loop through columns ?>
<th align="center" valign="middle"><?php echo $k; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach ($data as $k) : // Loop through each $data array() ?>
<tr>
<?php foreach ($k as $v) : // Let's display the records ?>
<td align="center" valign="middle"><?php echo $v; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
I also took the liberty to dynamically display the column names as table headers which should eliminate the need to manually add them later when your columns increase. If you would like to manually create them simply replace the top php portion with this one:
<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table
// Let's make sure we could establish a connection
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";
if(!$num_cols = $db->query($select_cols)){
die('There was an error running the query.');
}
$select_data = "SELECT * FROM $table_name ORDER BY `id` DESC LIMIT 0 , $num_cols->num_rows";
if(!$result = $db->query($select_data)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$data[] = $row; // Store the data into array to be used in the html table
}
$db->close(); // Close our connection
// print_r('<pre>');
// print_r($data);
// print_r('</pre>');
?>
and adjust the html code between <thead></thead>. This entire sample was put together pretty quickly so it could definitely be improved and adjusted to whatever needs. Please inspect it for any typos as well.

How can I get it so at the top of my search results page it says the amount of results found?

I have a results page and I would like there to be a bit at the top of the page where it says how many results were returned. How do I do this?
My code is
<?php
if(strlen(trim($_POST['search'])) > 0) {
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
mysql_connect ("3", "", "");
mysql_select_db ("");
if (!empty($_POST["search_string"]))
{
}
$query = "SELECT name,location,msg FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result) {
while ($row = mysql_fetch_array ($result)) { ?>
<center>
<table height="20" width="968" cellpadding="0" cellspacing="0">
<tr>
<td>
<table height="20" width="223" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="#045FB4"><?php echo $row[0]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
<td>
<table height="20" width="745" cellpadding="0" cellspacing="0">
<tr>
<td>
<font face="helvetica" size="2" color="black"><?php echo $row[1]; ?>
<?php echo $row[2]; ?></font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
<td align="right">
<font face="helvetica" size="2" color="red">See More...</font>
<hr size="1" color="#e6e6e6" width="100%"></hr>
</td>
</tr>
</table>
</td>
</tr>
</table>
<?php
}
}
}
?>
</center>
THANKS!
James
If you're going to keep it to one page then mysql_num_rows() will do the trick and you're good to go. If you use pagination on the other hand, then your SELECT query will have a LIMIT clause and a second query can be constructed using COUNT(*) on the same tables with the same WHERE clause.
$total_query = "SELECT COUNT(*) FROM contact WHERE name LIKE '%$search%' AND
location LIKE '%$searchterm%'"
I’m not trying to compete with the other fine answers. I’m posting this as an answer because it’s too big for a comment.
Since you asked in a comment what could be done to improve your HTML, I refactored your code a bit just to illustrate some things you could do. I also included mysql_num_rows($result) mentioned by the others for the sake of completion.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sample</title>
<style type="text/css">
table {
font-family: helvetica;
font-size: small;
width: 968px;
}
td {
border-bottom: 1px solid #e6e6e6;
}
.name {
color:#045FB4;
}
.msg {
color:black;
}
.more {
color:red;
}
</style>
</head>
<body>
<?php
if(strlen(trim($_POST['search'])) > 0):
$search = mysql_real_escape_string($_POST["search"]);
$searchterm = mysql_real_escape_string($_POST["searchterm"]);
mysql_connect ("localhost", "root", "");
mysql_select_db ("sample");
if (!empty($_POST["search_string"]))
{
$search_string = mysql_real_escape_string($_POST["search_string"]);
// more code here
}
$query = "SELECT name,location,msg FROM contact
WHERE name LIKE '%$search%'
AND location LIKE '%$searchterm%'";
$result = mysql_query ($query);
if ($result):
$num_rows = mysql_num_rows($result);
?>
<p>Found <?php echo $num_rows; ?> results.</p>
<table>
<?php
while ($row = mysql_fetch_array ($result)):
?>
<tr>
<td class="name"><?php echo $row['name']; ?></td>
<td class="msg"><?php echo $row['location'], ' ', $row['msg']; ?></td>
<td class="more">See More...</td>
</tr>
<?php
endwhile;
endif;
endif;
?>
</table>
</body>
</html>
Normally, I would put the CSS in a separate file, but this is only an example.
Some things to notice:
There’s only one table
There’s no style information in the HTML
It uses mysql_real_escape_string. Ideally you'd also want to use prepared statements, but I’ll leave that as a personal exercise for you. :)
Even this can be improved quite a bit, but it's a start.
Try using mysql_num_rows($query). I am no PHP expert but, from memory, that should do the trick. Just echo this wherever you want it.
$num_rows = mysql_num_rows($result);
Check out the documentation: http://php.net/manual/en/function.mysql-num-rows.php
Also you can use SQL_CALC_FOUND_ROWS and FOUND_ROWS():
$query = "SELECT SQL_CALC_FOUND_ROWS name,location,msg FROM contact WHERE name LIKE '%$search%' AND location LIKE '%$searchterm%'";
$result = mysql_query($query);
if ($result)
{
$rs_count = mysql_query("SELECT FOUND_ROWS();");
$counted = (int)mysql_result($rs_count, 0);
}

Categories