Query MySQL on PHP [closed] - php

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>';

Related

get all values of columns in sql php [duplicate]

I want to retrieve the values from a database table and show them in a html table in a page.
I already searched for this but I couldn't find the answer, although this surely is something easy (this should be the basics of databases lol). I guess the terms I've searched are misleading.
The database table name is tickets, it has 6 fields right now (submission_id, formID, IP, name, email and message) but should have another field called ticket_number.
How can I get it to show all the values from the db in a html table like this:
<table border="1">
<tr>
<th>Submission ID</th>
<th>Form ID</th>
<th>IP</th>
<th>Name</th>
<th>E-mail</th>
<th>Message</th>
</tr>
<tr>
<td>123456789</td>
<td>12345</td>
<td>123.555.789</td>
<td>John Johnny</td>
<td>johnny#example.com</td>
<td>This is the message John sent you</td>
</tr>
</table>
And then all the other values below 'john'.
Example taken from W3Schools: PHP Select Data from MySQL
<?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);
?>
It's a good place to learn from!
Try this: (Completely Dynamic...)
<?php
$host = "localhost";
$user = "username_here";
$pass = "password_here";
$db_name = "database_name_here";
//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = mysqli_connect($host, $user, $pass, $db_name);
//get results from database
$result = mysqli_query($connection, "SELECT * FROM products");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
$all_property[] = $property->name; //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
Here is an easy way to fetch data from a MySQL database using PDO.
define("DB_HOST", "localhost"); // Using Constants
define("DB_USER", "YourUsername");
define("DB_PASS", "YourPassword");
define("DB_NAME", "Yourdbname");
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset-utf8mb4", DB_USER, DB_PASS);
$print = ""; // assign an empty string
$stmt = $dbc->query("SELECT * FROM tableName"); // fetch data
$stmt->setFetchMode(PDO::FETCH_OBJ);
$print .= '<table border="1px">';
$print .= '<tr><th>First name</th>';
$print .= '<th>Last name</th></tr>';
while ($names = $stmt->fetch()) { // loop and display data
$print .= '<tr>';
$print .= "<td>{$names->firstname}</td>";
$print .= "<td>{$names->lastname}</td>";
$print .= '</tr>';
}
$print .= "</table>";
echo $print;
Learn more about PHP and the MySQLi Library at PHP.net.
First, start a connection to the database. Do this by making all the string variables needed in order to connect, adjusting them to fit your environment, then creating a new connection object with new mysqli() and initializing it with the previously made variables as its parameters. Now, check the connection for errors and display a message whether any were found or not. Like this:
<?php
$servername = "localhost";
$username = "root";
$password = "yourPassword";
$database = "world";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $database);
echo "Connected successfully<br>";
?>
Next, make a variable that will hold the query as a string, in this case its a select statement with a limit of 100 records to keep the list small. Then, we can execute it by calling the mysqli::query() function from our connection object. Now, it's time to display some data. Start by opening up a <table> tag through echo, then fetch one row at a time in the form of a numerical array with mysqli::fetch_row() which can then be displayed with a simple for loop. mysqli::field_count should be self explanatory. Don't forget to use <td></td> for each value, and also to open and close each row with echo"<tr>" and echo"</tr>. Finally we close the table, and the connection as well with mysqli::close().
<?php
$query = "select * from city limit 100;";
$queryResult = $conn->query($query);
echo "<table>";
while ($queryRow = $queryResult->fetch_row()) {
echo "<tr>";
for($i = 0; $i < $queryResult->field_count; $i++){
echo "<td>$queryRow[$i]</td>";
}
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
First, connect to the database:
$conn=mysql_connect("hostname","username","password");
mysql_select_db("databasename",$conn);
You can use this to display a single record:
For example, if the URL was /index.php?sequence=123, the code below would select from the table, where the sequence = 123.
<?php
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>
<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>
</table>';
?>
Or, if you want to list all values that match the criteria in a table:
<?php
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>';
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>';
}
echo '</table>';
?>
Surely a better solution would by dynamic so that it would work for any query without having to know the column names?
If so, try this (obviously the query should match your database):
// You'll need to put your db connection details in here.
$conn = new mysqli($server_hostname, $server_username, $server_password, $server_database);
// Run the query.
$result = $conn->query("SELECT * FROM table LIMIT 10");
// Get the result in to a more usable format.
$query = array();
while($query[] = mysqli_fetch_assoc($result));
array_pop($query);
// Output a dynamic table of the results with column headings.
echo '<table border="1">';
echo '<tr>';
foreach($query[0] as $key => $value) {
echo '<td>';
echo $key;
echo '</td>';
}
echo '</tr>';
foreach($query as $row) {
echo '<tr>';
foreach($row as $column) {
echo '<td>';
echo $column;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
Taken from here: https://www.antropy.co.uk/blog/handy-php-snippets/
mysql_connect("localhost","root","");
mysql_select_db("database");
$query=mysql_query("select * from studenti");
$x=#mysql_num_rows($query);
echo "<a href='file.html'>back</a>";
echo "<table>";
$y=mysql_num_fields($query);
echo "<tr>";
for($i=0 ,$i<$y,$i++)
{
$values=mysql_field_name($query,$i);
echo "<th>$values</th>";
}
echo "</tr>";
while(list($p ,$n $your_table_list)=mysql_fetch_row($query))
{
print("<tr>\n".
"<td>$p</td>".
"</tr>/n");
}
?>
<?php
$mysql_hostname = "localhost";
$mysql_user = "ram";
$mysql_password = "ram";
$mysql_database = "mydb";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Oops some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Oops some thing went wrong");// we are now connected to database
$result = mysql_query("SELECT * FROM users"); // selecting data through mysql_query()
echo '<table border=1px>'; // opening table tag
echo'<th>No</th><th>Username</th><th>Password</th><th>Email</th>'; //table headers
while($data = mysql_fetch_array($result))
{
// we are running a while loop to print all the rows in a table
echo'<tr>'; // printing table row
echo '<td>'.$data['id'].'</td><td>'.$data['username'].'</td><td>'.$data['password'].'</td><td>'.$data['email'].'</td>'; // we are looping all data to be printed till last row in the table
echo'</tr>'; // closing table row
}
echo '</table>'; //closing table tag
?>
it would print the table like this
just read line by line so that you can understand it easily..
OOP Style :
At first connection with database.
<?php
class database
{
public $host = "localhost";
public $user = "root";
public $pass = "";
public $db = "db";
public $link;
public function __construct()
{
$this->connect();
}
private function connect()
{
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->link;
}
public function select($query)
{
$result = $this->link->query($query) or die($this->link->error.__LINE__);
if($result->num_rows>0)
{
return $result;
}
else
{
return false;
}
}
?>
Then :
<?php
$db = new database();
$query = "select * from data";
$result = $db->select($query);
echo "<table>";
echo "<tr>";
echo "<th>Name </th>";
echo "<th>Roll </th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> $row[name]</td>";
echo "<td> $row[roll]</td>";
echo "</tr>";
}
echo "</table>";
?>

How i can retrieve data of a individual by s_no

i have 2 html table one is table.php and anther one is viewdata.php. In frist table there arenumber of rows and data is extracting from mysql database. If i will click on serial no 1 of my html table data then the detail of serial no 1 must show in another table and i tried so. But i dont understand how to do it.
table.php
this is the html table
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass)
or die ('Error connecting to mysql');
$dbname = 'form_db';
mysql_select_db($dbname);
$query = "SELECT * FROM form";
$result = mysql_query($query)
or die(mysql_error());
print "
<table id=\"AutoNumber2\" border=\"1\">
<tr>
<th>S.no</th>
<th>Title of thesis:</th>
<th>View detail:</th>
</tr>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
print "<tr>";
print "<td>" . $row['s_no'] . "</td>";
print "<td>" . $row['title of thesis'] . "</td>";
print "</tr>";
}
print "</table>";
?>
dataview.php another table
<?php
$query = "SELECT * FROM form";
$result3 = mysql_query($query)
or die(mysql_error());
$result3 = mysql_query("SELECT * FROM form where s_no='11'");
while($row3 = mysql_fetch_array($result3, MYSQL_ASSOC)){
$s_no=$row3['s_no'];
$obs_time=$row3['obs_time'];
$title=$row3['title'];
$type=$row3['type'];
$thesis=$row3['thesis'];
$year=$row3['year'];
$proposer=$row3['proposer'];
$institute=$row3['institute'];
$email=$row3['email'];
$present=$row3['present'];
$date=$row3['date'];
}
?>
Here I have mannualy select the s_no'11'. I dont know how i can pass the s_no automatically simply clicking on the row (view detail) which i want to show in another table with its detail. thank you so much./!!
send the variable via the URL using $_GET
dbconnect.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'form_db';
mysql_select_db($dbname);?>
table.php
include('dbconnect.php');
$query = "SELECT * FROM form";
$result = mysql_query($query) or die(mysql_error());
print "
<table id=\"AutoNumber2\" border=\"1\">
<tr>
<th>S.no</th>
<th>Title of thesis:</th>
<th>View detail:</th>
</tr>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
print "<tr>";
print "<td>". $row['s_no'] . "</td>";
print "<td>" . $row['title of thesis'] . "</td>";
print "</tr>";
}
print "</table>";?>
dataview.php
<?php
include('dbconnect.php');
$sn= $_GET['s_no'];
$sql = "SELECT * FROM form where s_no=". $sn;
$result3 = mysql_query($sql);
while($row3 = mysql_fetch_array($result3, MYSQL_ASSOC)){
$s_no=$row3['s_no'];
$obs_time=$row3['obs_time'];
$title=$row3['title'];
$type=$row3['type'];
$thesis=$row3['thesis'];
$year=$row3['year'];
$proposer=$row3['proposer'];
$institute=$row3['institute'];
$email=$row3['email'];
$present=$row3['present'];
$date=$row3['date'];
}
?>

Re-factoring this mysql table display code

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>';

How to fetch data from mySQL by filtering by email?

i am trying to fetch data from mySQL and I would like to filter the result by email.
The only problem is, I want to fetch data from a booking DB, while user emails are stored in a different DB.
When a user books a session, his email is fetched using
<?= $fgmembersite->UserEmail(); ?>
and it is saved in the booking DB under reservation_email
I tried to use WHERE reservation_email=<?= $fgmembersite->UserEmail(); ?>.
**My question is, what can I do, to fetch data into a table by filtering using an email address from a different DB? **
<?php
$dbhost = 'localhost';
$dbuser = 'user';
$dbpass = 'pwd';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'dbname';
mysql_select_db($dbname);
$query = "SELECT * FROM booking_reservation WHERE reservation_email='<?= $fgmembersite->UserEmail(); ?>' ";
$result = mysql_query($query)
or die(mysql_error());
print "
<table class='table table-striped'><tr>
<td width=100>Name:</td>
<td width=100>ID Skype:</td>
<td width=100>indirizzo email:</td>
<td width=100>Richiesta:</td>
</tr>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
print "<tr>";
print "<td>" . $row['reservation_name'] . "</td>";
print "<td>" . $row['reservation_surname'] . "</td>";
print "<td>" . $row['reservation_email'] . "</td>";
print "<td>" . $row['reservation_message'] . "</td>";
print "</tr>";
}
print "</table>";
?>
If I understand the problem correctly you should be able to use the database name in the query.
SELECT * FROM `db1`.`table` AS t1 JOIN `db2`.`table` AS t2 ON ...
I am not sure just how you are retrieving the email address from the first db?
But for this I would use SESSIONS in the form of:
<?php
session_start();
//your authentication script
//then
$_SESSION["email"] = $fgmembersite->UserEmail;
//anythink else you need to do
?>
Then in your script
$query = "SELECT * FROM booking_reservation WHERE reservation_email=".$_SESSION['email'];
I have not tested this, but should put you in the right direction

Show values from a MySQL database table inside a HTML table on a webpage

I want to retrieve the values from a database table and show them in a html table in a page.
I already searched for this but I couldn't find the answer, although this surely is something easy (this should be the basics of databases lol). I guess the terms I've searched are misleading.
The database table name is tickets, it has 6 fields right now (submission_id, formID, IP, name, email and message) but should have another field called ticket_number.
How can I get it to show all the values from the db in a html table like this:
<table border="1">
<tr>
<th>Submission ID</th>
<th>Form ID</th>
<th>IP</th>
<th>Name</th>
<th>E-mail</th>
<th>Message</th>
</tr>
<tr>
<td>123456789</td>
<td>12345</td>
<td>123.555.789</td>
<td>John Johnny</td>
<td>johnny#example.com</td>
<td>This is the message John sent you</td>
</tr>
</table>
And then all the other values below 'john'.
Example taken from W3Schools: PHP Select Data from MySQL
<?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);
?>
It's a good place to learn from!
Try this: (Completely Dynamic...)
<?php
$host = "localhost";
$user = "username_here";
$pass = "password_here";
$db_name = "database_name_here";
//create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = mysqli_connect($host, $user, $pass, $db_name);
//get results from database
$result = mysqli_query($connection, "SELECT * FROM products");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
$all_property[] = $property->name; //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
Here is an easy way to fetch data from a MySQL database using PDO.
define("DB_HOST", "localhost"); // Using Constants
define("DB_USER", "YourUsername");
define("DB_PASS", "YourPassword");
define("DB_NAME", "Yourdbname");
$dbc = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset-utf8mb4", DB_USER, DB_PASS);
$print = ""; // assign an empty string
$stmt = $dbc->query("SELECT * FROM tableName"); // fetch data
$stmt->setFetchMode(PDO::FETCH_OBJ);
$print .= '<table border="1px">';
$print .= '<tr><th>First name</th>';
$print .= '<th>Last name</th></tr>';
while ($names = $stmt->fetch()) { // loop and display data
$print .= '<tr>';
$print .= "<td>{$names->firstname}</td>";
$print .= "<td>{$names->lastname}</td>";
$print .= '</tr>';
}
$print .= "</table>";
echo $print;
Learn more about PHP and the MySQLi Library at PHP.net.
First, start a connection to the database. Do this by making all the string variables needed in order to connect, adjusting them to fit your environment, then creating a new connection object with new mysqli() and initializing it with the previously made variables as its parameters. Now, check the connection for errors and display a message whether any were found or not. Like this:
<?php
$servername = "localhost";
$username = "root";
$password = "yourPassword";
$database = "world";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $database);
echo "Connected successfully<br>";
?>
Next, make a variable that will hold the query as a string, in this case its a select statement with a limit of 100 records to keep the list small. Then, we can execute it by calling the mysqli::query() function from our connection object. Now, it's time to display some data. Start by opening up a <table> tag through echo, then fetch one row at a time in the form of a numerical array with mysqli::fetch_row() which can then be displayed with a simple for loop. mysqli::field_count should be self explanatory. Don't forget to use <td></td> for each value, and also to open and close each row with echo"<tr>" and echo"</tr>. Finally we close the table, and the connection as well with mysqli::close().
<?php
$query = "select * from city limit 100;";
$queryResult = $conn->query($query);
echo "<table>";
while ($queryRow = $queryResult->fetch_row()) {
echo "<tr>";
for($i = 0; $i < $queryResult->field_count; $i++){
echo "<td>$queryRow[$i]</td>";
}
echo "</tr>";
}
echo "</table>";
$conn->close();
?>
First, connect to the database:
$conn=mysql_connect("hostname","username","password");
mysql_select_db("databasename",$conn);
You can use this to display a single record:
For example, if the URL was /index.php?sequence=123, the code below would select from the table, where the sequence = 123.
<?php
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$result=mysql_fetch_array($rs);
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>
<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>
</table>';
?>
Or, if you want to list all values that match the criteria in a table:
<?php
echo '<table>
<tr>
<td>Forename</td>
<td>Surname</td>
</tr>';
$sql="SELECT * from table where sequence = '".$_GET["sequence"]."' ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<tr>
<td>'.$result["forename"].'</td>
<td>'.$result["surname"].'</td>
</tr>';
}
echo '</table>';
?>
Surely a better solution would by dynamic so that it would work for any query without having to know the column names?
If so, try this (obviously the query should match your database):
// You'll need to put your db connection details in here.
$conn = new mysqli($server_hostname, $server_username, $server_password, $server_database);
// Run the query.
$result = $conn->query("SELECT * FROM table LIMIT 10");
// Get the result in to a more usable format.
$query = array();
while($query[] = mysqli_fetch_assoc($result));
array_pop($query);
// Output a dynamic table of the results with column headings.
echo '<table border="1">';
echo '<tr>';
foreach($query[0] as $key => $value) {
echo '<td>';
echo $key;
echo '</td>';
}
echo '</tr>';
foreach($query as $row) {
echo '<tr>';
foreach($row as $column) {
echo '<td>';
echo $column;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
Taken from here: https://www.antropy.co.uk/blog/handy-php-snippets/
mysql_connect("localhost","root","");
mysql_select_db("database");
$query=mysql_query("select * from studenti");
$x=#mysql_num_rows($query);
echo "<a href='file.html'>back</a>";
echo "<table>";
$y=mysql_num_fields($query);
echo "<tr>";
for($i=0 ,$i<$y,$i++)
{
$values=mysql_field_name($query,$i);
echo "<th>$values</th>";
}
echo "</tr>";
while(list($p ,$n $your_table_list)=mysql_fetch_row($query))
{
print("<tr>\n".
"<td>$p</td>".
"</tr>/n");
}
?>
<?php
$mysql_hostname = "localhost";
$mysql_user = "ram";
$mysql_password = "ram";
$mysql_database = "mydb";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Oops some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Oops some thing went wrong");// we are now connected to database
$result = mysql_query("SELECT * FROM users"); // selecting data through mysql_query()
echo '<table border=1px>'; // opening table tag
echo'<th>No</th><th>Username</th><th>Password</th><th>Email</th>'; //table headers
while($data = mysql_fetch_array($result))
{
// we are running a while loop to print all the rows in a table
echo'<tr>'; // printing table row
echo '<td>'.$data['id'].'</td><td>'.$data['username'].'</td><td>'.$data['password'].'</td><td>'.$data['email'].'</td>'; // we are looping all data to be printed till last row in the table
echo'</tr>'; // closing table row
}
echo '</table>'; //closing table tag
?>
it would print the table like this
just read line by line so that you can understand it easily..
OOP Style :
At first connection with database.
<?php
class database
{
public $host = "localhost";
public $user = "root";
public $pass = "";
public $db = "db";
public $link;
public function __construct()
{
$this->connect();
}
private function connect()
{
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->db);
return $this->link;
}
public function select($query)
{
$result = $this->link->query($query) or die($this->link->error.__LINE__);
if($result->num_rows>0)
{
return $result;
}
else
{
return false;
}
}
?>
Then :
<?php
$db = new database();
$query = "select * from data";
$result = $db->select($query);
echo "<table>";
echo "<tr>";
echo "<th>Name </th>";
echo "<th>Roll </th>";
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> $row[name]</td>";
echo "<td> $row[roll]</td>";
echo "</tr>";
}
echo "</table>";
?>

Categories