MySQL/PHP connection ok, sql statement doesn't work - php

How can I get this to echo or print out the results of a select statement via php?
<?php
$username = "root";
$password = "root";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>
<?php
$query="SELECT * FROM mydb.product";
$result=mysql_query($query);
echo "$result";
echo $result;
?>
I've gotten this far now, but it still returns nothing. Does the problem lie within my mysql table? Or does it fall somewhere else
<?php
$username = "root";
$password = "root";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$sth = $db->prepare("SELECT * FROM mydb.test;");
$sth->execute();
$result = $sth->fetchAll();
?>
<h1> Im here</h1>
<?php
foreach ($result as $row) {
echo "<tr>";
echo "<td>{$row['name']}</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
?>
<h1> Im still here</h1>
Thanks for all the help

You need to look through the results. If there are, say, 3 columns in each row then your code would look something like this:
for($i=0;$i<mysql_num_rows($result);$i++) {
$row_array=mysql_fetch_row($result);
echo($row_array[0]." ".$row_array[1]." ".$row_array[2]."<br />");
}

As suggested in the comments, you'll have to loop through the fetched results:
$query="SELECT * FROM mydb.product";
$result=mysql_query($query);
// Add these lines:
while ($row = mysql_fetch_assoc($result)) {
var_dump($row);
// each item from the row could be used like this:
// echo $row['field'];
}
More information can be found here: http://php.net/manual/en/function.mysql-query.php
Please note that mysql_query is depricated, and you should consider switching to mysqli (http://php.net/manual/en/book.mysqli.php) or PDO (http://php.net/manual/en/ref.pdo-mysql.php)

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);
?>

echo something out MySQL database

I am trying to get a question with answers out of my database. I just want to get one thing out of the database and not with a row. I thought this would work but it puts out this: Resource id #4 can someone explains what I am missing.
Thanks :)
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('lotto');
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1';
$test = mysql_query($sql);
echo $test;
?>
As said at least 10000 times everywhere in internet, never use MySQL_ ! (If your are trying to learn something new by using tutorials over internet, don't use old ones)
I recommend to use PDO which is modern API in PHP and a lot more secure when using it correctly with prepared statement ! But you can also use MYSQLI which is more similar to the MYSQL !
You have to export your data from return array :
Using PDO :
$db = new PDO ("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);
$query = $db -> prepare ("SELECT * FROM vraag1");
$query -> execute (array ());
$rows = $query -> fetchAll (PDO::FETCH_ASSOC);
foreach ($rows as $row)
{
echo $id = $row["id"];
echo $vraag = $row["vraag "];
echo $AntwA = $row["AntwA "];
echo $AntwB = $row["AntwB "];
echo $AntwC = $row["AntwC "];
echo $AntwD = $row["AntwD "];
}
Using MYSQLI :
$db = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$query = "SELECT * FROM vraag1";
$rows = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($rows))
{
echo $row["id"];
echo $row["vraag"];
echo $row["AntwA"];
echo $row["AntwB"];
echo $row["AntwC"];
echo $row["AntwD"];
}
First of all the mysql function you are using is depreciated and no longer supported. you should use mysqli or pdo instead with prepared statements.
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "lotto";
// Create connection
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1";
$test = mysqli_query($conn, $sql);
if (mysqli_num_rows($test) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($test)) {
echo "ID : ".$row['id']."<br>";
echo "vraag :".$row['vraag']."<br>";
echo "AntwA :".$row['AntwA']."<br>";
echo "AntwB :".$row['AntwB']."<br>";
echo "AntwC :".$row['AntwC']."<br>";
echo "AntwD :".$row['AntwD']."<br>";
}
} else {
echo "no results found";
}
mysqli_close($conn);
?>
For select function mysql_query() returns a resource on success, or FALSE on error.
so your assignment statement
$test = mysql_query($sql);
assign the resource to $test.
if you want the data inside the resource you can do
while($row= mysql_fetch_assoc($test)):
print_r($row);
endwhile;
also you can access the $row['column_name']
If you want to return only one row you can do this limit in query
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1 limit 1';
You need to add something like the following:
while($row = mysql_fetch_array($result)){
echo $row['id'];
echo $row['vraag'];
echo $row['AntwA'];
echo $row['AntwB'];
echo $row['AntwC'];
echo $row['AntwD'];
}
use mysqli instead of mysql
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
mysqli_select_db('lotto');
$sql = 'SELECT id, vraag, AntwA, AntwB, AntwC, AntwD FROM vraag1';
$test = mysqli_query($sql);
echo $test;
?>

How to show table from MySQL database using php and html

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.

Trying to print data from my MYSQL database, doesn't show anything nor any errors

I am trying the fetch the data from my database sunypub from the table journal.
Out of many attributes, I am trying to get three atrributes which are of my use on the webpage through PHP, but it is not showing anything on the webpage.
This is the option which is directing to the page display.php, which will show me the attributes value of attribute jname, date and location from the table journal
<div align = "left">
<form action = "display.php">
<input type = "submit" value = "Show all the Conference List">
</form>
</div>
display.php:
<? php
// Create Local variable
$taken = "false";
$database = "sunypub";
$password = "";
$username = "root";
// Connect to database
$con = mysql_connect('localhost', $username, $password, $database) or die ("Unable to connect");
#mysql_select_db($database) or die("Database not found");
echo "Database Connected";
$query = "select * from journal ";
$result = mysql_query($con,$query) or die("Strange Error");
echo "Database Connected";
while( $row = mysql_fetch_assoc( $result, MYSQL_ASSOC ) ){
echo $row['jname'];
echo $row['date'];
echo $row['location'];
echo "Database Connected";
}
mysql_close($con);
?>
mysql_* is deprecated and is removed in new PHP version. So I highly recommend you to change to PDO or mysqli_* prepared statements, instead of fixing your old code.
So your code could look something like this:
(Note that you have to remove the space here: <? php)
<?php
// Create Local variable
$taken = "false";
$dbhost = "localhost";
$dbname = "sunypub";
$dbpass = "";
$dbuser = "root";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM journal";
foreach($dbh->query($sql) as $row) {
echo $row['jname'];
echo $row['date'];
echo $row['location'];
echo "Database Connected";
}
$dbh = NULL;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>

MySQL query using PHP

I cant seem to get this code to work. It keeps giving me the error "sorry: query failed". There is connection to the database cause if i input a wrong password it will give the error "mysql connection failed". The table pet is already created and populated with data. Please I need help
<?php
$conn = mysql_connect ("localhost", "vistor", "visitor", "test")
or die ("sorry: Mysql connection failed");
$query = "select * from pet";
$result = mysql_query ($query,$conn)
or die ("sorry: query failed");
while($row = mysql_fetch_array($result)) {
echo $row['code'], " ", $row['name'];
echo "<br>";
}
mysql_close($conn);
?>
Donny gave me the below code and i added some css to make it appear as a table but i am suspecting i have the coding wrong as I am getting errors. thanks
<html>
<head>
<title> php test script - hope this works </title>
</head>
<body>
<h1>php & mysql connection</h1>
<hr>
<?php
$db_host = "localhost";
$db_username = "vistor";
$db_pass = "visitor";
$db_name = "test";
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$query = $db->query('SELECT * FROM pet');
echo "<table border = '2'>"
<tr>
<th>id</th>
<th>name</th>
</tr>
while ($row = $query->fetch())
{
echo "<tr>";
echo "<td>" . $row['id'] ."</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "</tr>;
}
echo "</table>";
?>
</body>
</html>
Can you provide the full code for the database connection and query?
Keeping in mind that mysql_* functions have been deprecated in PHP, if you still want to use them, you should be able to do something like this:
<?php
//create connection to MySQL
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');
//select database
mysql_select_db('mysql_dbname', $link);
//create and execute query
$sql = 'SELECT foo FROM bar WHERE id = 42';
$result = mysql_query($sql, $link);
?>
You should learn how to write the code in a prepared PDO statement. Since MySQL will be deprecated and writing it in MySQL can get you into trouble with injections. This is how you would write this code in a prepared PDO statement. You can write it in MySQLI, but the only thing is you would not be able to use your code with any other databases besides MySQL. With PDO you can use your code with any database like SQL, Access and more.
<?php
$db_host = "localhost";
$db_username = "visitor";
$db_pass = "visitor";
$db_name = "test";
$db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$query = $db->query('SELECT * FROM pet');
while ($row = $query->fetch()) {
echo $row['code'], " ", $row['name'];
}
?>

Categories