How to show table from MySQL database using php and html - php

I am trying to connect my html page with MySQL database to show data from one specific table to my page, but I always get an error actually it just goes to die part of an SQL code. I am really new to PHP programming so please can someone help me, what am I doing wrong?
Here is my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AJDE</title>
</head>
<?php
$servername = "localhost";
$username = "******";
$password = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "select * from PERCENTILE";
$result = mysqli_query($conn,$query);
if(!$result) {
die ("Umro!");
}
/* close connection */
$mysqli->close();
?>
<body>
</body>
</html>
Thank you!

Do you want to show the table as a HTML table or just an array?
The following is what I did to display my table as a HTML table:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
echo("<div class = 'data_wrapper'>");
// Display Header of the table
$fieldcount=mysqli_num_fields($result); //value = number of columns
$row = mysqli_fetch_assoc($result); //Fetch a result row as an associative array:
//array to string conversion
echo("<table id='example' class='table table-striped table-bordered' cellspacing='0' width='100%'>");
echo("<thead> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </thead>");
//Footer
echo("<tfoot> <tr>");
foreach($row as $item){
echo "<th>" .$item. "</th>";
}
echo("</tr> </tfoot>");
//Display Data within the table
echo("<tbody>");
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
foreach ($row as $item){
echo "<td contenteditable = 'true'>" . $item . "</td>"; //Change contenteditable later
//Editable data should be constricted, int = numbers only, string = words, date = date
}
echo "</tr>";
}
echo("<tbody>");
echo "</table>";
echo("</div>");
}
The following is just displaying as an array:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '*****';
$dbname = 'dbname';
$selectedTable = 'whateverTableYouWant';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
if (!$conn){
die('cannot connect to mysql');
}
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
while ($row = mysqli_fetch_array($result)){
print_r($row);
}
}

Please change the connection string like mentioned below.
<?php
$con = mysqli_connect("localhost","username","password","dbname");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Please let me know if you've any queries.

I Think you need to select a database where you will run the query:
Try with this code:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with (so replace the database name examples)
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM PERCENTILE");
//fetch the data from the database and display results
//replace id,name,year with the columns you have on your table PERCENTILE and you want to show
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'name'}."Year: ". $row{'year'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>
Hope it helps,
Vince.

Related

Trying to echo out every name in database table inside hrml list

I have been trying to echo out database data through a while loop now for awhile but it doesn't work, I can't find where the issue is. I have tried echoing out data manually and that works just fine.
<?php $results = mysqli_query($con,"SELECT * FROM guestbook ORDER BY id DESC"); ?>
<?php while ($row = mysqli_fetch_assoc($results)) : ?>
<li>
<?php echo $row['message']; ?>
</li>
<?php endwhile ?>
First of all make sure you are connected to the database. I don't know if you omitted that on purpose or not. Also, check if the connection is established.
<?php
//Insert your server info here
$servername = "servername";
$username = "root";
$password = "root";
$dbname = "test_database";
// Create and check your connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM guestbook ORDER BY id DESC";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<li>' . row["message"] . '</li>';
}
} else {
// Your query produced 0 results
echo "Empty result!";
}
// Remember to close the connection
mysqli_close($conn);
?>

Need help to display data from mysql database

I would need some help with showing data that I have on my database but I can't seen to be able to.`
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
$connect = mysqli_connect($servername, $username, $password, $dbname) or die ("connection failed");
//Query
$query = "SELECT * FROM 'Students'";
mysqli_master_query($dbname, $query) or die ("Error while Query");
$result = mysqli_master_query($dbname, $query);
$row = mysql_fetch_array($result);
while ($row = mysql_fetch_array($result)) {
echo "<p>".$row['Name']."</p>";
};
mysql_close($connect);
?>`
I am pretty new to this so I could have missed something simple. Any help appreciated.
Below is a sample code of the normal procedure to connect to a database and to select data from it. Please follow this type of coding since MySQL is now deprecated and MySQLi is used.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$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";
}
mysqli_close($conn);
?>
For further reference check out http://php.net/manual/en/book.mysqli.php and also https://www.w3schools.com/php/php_mysql_insert.asp

How to retrieve images from database in php

I have a database which has a table called 'propImages' and there are two columns.- 'pid' and 'location'.
And i have data in the database where multiple images can contained by single pid.
image contains database data
now i want to retrieve images from database according to given pid. there can be more than one image.
All i know it there should be an iteration to retrieve images.
I want to display images in HTML .
can you please show me the way to do it in php?
Thanks in advance guys
This may help you
<?php
include 'inc/database.php';
$conn = new mysqli($servername, $username, $password, $database);
$propid = $_GET['propid'];
$sql = "SELECT * FROM propImages WHERE propid='" . $propid . "';";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<img src=" . $row['image'] . ">";
}
}
else {
echo "No results";
}
?>
in the inc/database.php :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "database";
?>
To see how it works try visiting : file.php?propid=22
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "databasename";
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
//create sql
$sql = "SELECT * FROM `propImages` where pid='$YOUR_PID'";
$result = mysqli_query($con, $sql);
$row = mysqli_num_rows($result);
//retrive data print here
if($row > 0){
while($col = mysqli_fetch_assoc($result))
{
echo $col['location'];
}
} else {
echo 'no result found.';
}
?>
wish it helps

PDO SUM MYSQL table

I am learning as i go and been picking up snippets of code as i go and been working on this for the past few days and now i have thrown the towel in to seek help.
I am trying to calculate the sum of 2 columns in my database using PDO.
here is my code
<?php
$host = "localhost";
$db_name = "dbname";
$username = "root";
$password = "root";
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}
// show error
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$query = "SELECT SUM (fill_up) AS TotalFill,
SUM (mileage_covered) AS Totalmiles
FROM fuel_cost";
$row = $query->fetch(PDO::FETCH_ASSOC);
$total_fill = $row['TotalFill'];
$total_miles = $row['Totalmiles'];
$myanswer = $total_fill/$total_miles;
//display the answer
echo $myanswer
?>
I have also checked my database table and both columns are varchar(32)
the error I am getting is Call to a member function fetch() on a non-object
I have searched into this but not sure what's the issue with the above code
Thank You in advance
Try this code :-
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT SUM (fill_up) AS TotalFill,
SUM (mileage_covered) AS Totalmiles
FROM fuel_cost";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$total_fill = $row['TotalFill'];
$total_miles = $row['Totalmiles'];
$myanswer = $total_fill / $total_miles;
//display the answer
echo $myanswer;
die;
}
} else {
echo "0 results";
}
$conn->close();
?>

How can I print all my database row from PHP?

I am trying to print all the rows in my database say 'student'. I am trying with many of codes with while loops and even examples from w3school. But, it's not working. Here's a simple code of php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn) {
die('Could not connect to MySql'.mysql_error());
}
mysql_select_db("StudDatabase") or die(mysql_error());
$sql = "SELECT * FROM Student";
mysql_query($sql);
mysql_close($conn);
?>
I am working in wamp server 2.2
Your code don't print the result of the query.
Try to add this code:
$results = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($results)){
foreach($row as $cname => $cvalue){
print "$cname: $cvalue\t";
}
print "\r\n";
}
But you should consider using PDO, mylsql is deprecated : http://php.net/manual/en/pdo.connections.php
$database = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($database->query('SELECT * FROM `Student`') as $row) {
print_r($row);
}

Categories