MySQL query using PHP - 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'];
}
?>

Related

Select Syntax from a Get variable

I want to select a value from the database with variables I get from $_GET, but it doesn't show any results. Could any one help me find what is wrong with my code?
here is my first page how i get the value to GET:
<?php
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<tr>
<td><?= $row['subject'] ?></td>
<td><?= $row['location'] ?></td>
<td><?= $row['geo'] ?></td>
<td><?= $row['date'] ?></td>
<td><?= $row['piority'] ?></td>
</tr>
<?php
}
}
?>
and here is my second page that i want to get data from database with subject variable from first page:
<?php
$varPage = $_GET['subject'];
$servername = "localhost";
$username = "bayansh_user";
$password = "u)nHf,Accmo)";
$dbname = "bayansh_bmc";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn,"SELECT `date` FROM `editor` WHERE subject = '.$varPage.'");
while($row = mysqli_fetch_array($result))
?>
and now i want to write the date here is my code:
<p style="font-family:B Zar; direction:rtl; font-size:165%;"> <?= $row['date'] ?> </p>
but it writes nothing.
Is there anything wrong with my code?
There seems to be an oversight on your part with regards to your SQL. You have an extra-dot, which likely was a Typo. Try addressing that part and your code would most likely work as you expected. Some Guys here have suggested working with Prepared Statement (which is quite necessary) in which case this Snippet would use PDO as opposed to MySQLi... although the principles are not so extremely different.
<?php
$varPage = $_GET['subject'];
$servername = "localhost";
$username = "bayansh_user";
$password = "u)nHf,Accmo)";
$dbname = "bayansh_bmc";
$dbh = null;
// USING PDO INSTEAD::
$dsn = 'mysql:host=' . $servername . ';dbname=' . $dbname;
try {
$dbh = new PDO($dsn, $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
// USING PREPARED STATEMENT... NOTICE "=:SBJ"
$sql = "SELECT `date` FROM `editor` WHERE subject=:SBJ";
// USING PREPARED STATEMENT CONTINUED: NOTICE "$dbh->prepare()"
$stmt = $dbh->prepare($sql);
// PASSING VALUES: NOTICE "['SBJ'=>$varPage]"
$stmt->execute( array('SBJ'=>$varPage) );
$resultSet = $stmt->fetchAll(PDO::FETCH_OBJ);
// LOOP THROUGH THE RESULT-SET AND DO SOME THINGS WITH THE DATA...
foreach($resultSet as $intKey=>$objData){
var_dump($objData->date); //<== DUMP SOME DATA TO THE STREAM
}
You should use the following code
$result = mysqli_query($conn,"SELECT `date` FROM `editor` WHERE subject = '".$varPage."'");

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.

Cannot access data from mysql table using object oriented style of php-mysql

I'm a newbie at PHP. I'm simply trying to access my database and here is the code. I'm using the object oriented style for accessing the database.
It says "Trying to get property of non-object on line 25".
What am I missing?
<?php
$servername = "localhost";
//$username = "";
//$password = "";
$database = "MyPetProject";
$conn = new mysqli ($servername, $database);
if ($conn-> connect_error)
{
die ("Connection failed : " . $conn->connect_error);
}
else
{
echo "Connection Successfull";
}
$sql = "SELECT * FROM User";
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while( $row = $result->fetch_assoc())
{
echo $row["Sr.no"] . " " . $row["Name"] . " " . $row["Online"];
}
}
else
{
echo "0 results";
}
echo ("hello world");
$conn->close();
?>
Edit the following:
while( $row = $result->fetch_assoc($result))
And it should work
Answering my own question here.
I had commented $username and $password.
These are mandatory parameters for mysqli. The rest of the code is perfectly fine.
You should need a username and password for accessing mysql databases .
$mysqli = new mysqli("localhost", "user", "password", "database");
which is the second and third parameters respectively.
You could find all related documentation in this link.
http://php.net/manual/en/mysqli.quickstart.connections.php

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/PHP connection ok, sql statement doesn't work

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)

Categories