This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 3 years ago.
I have many simple PHP files with MySQL queries that I need to modify since my webhost migrated from PHP5 -> PHP7. I am pretty much a PHP/MySQL beginner trying to wrap my head around the changes from MySQL to MySQLi.
I've begun reading the PHP docs re: MySQLi but am getting stuck on mysqli_query at the moment.
Here is the MySQLi code I've tried so far:
<?php
$con = mysqli_connect("localhost”, “my_user","my_password,"my_db”);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$result = mysqli_query("SELECT image, caption
FROM tbllinkcat, tblimages
WHERE tbllinkcat.catid = tblimages.catid
AND tbllinkcat.catid=1;");
while($row = mysql_fetch_array($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
mysql_close($con);
?>
I'm pretty sure the mysqli_connect code is working but I get errors on the mysqli_query code (error: Warning: mysqli_query() expects at least 2 parameters.
And I am pretty sure I will get errors on the mysql_fetch_array too once I correct mysqli_query. So for now I was wondering if someone could just show me an example of a mysqli_query that would work for the specific SQL statements in my code above? I will continue reading the PHP docs for MySQli and mysqli_query. Thank you.
mysqli_query needs two parameters:
Your database connection
A query
That will result in this:
$result = mysqli_query($con, "SELECT image, caption FROM tbllinkcat, tblimages WHERE tbllinkcat.catid = tblimages.catid AND tbllinkcat.catid=1;");
You also have some weird looking quotation marks in your connect function, correct them:
$con = mysqli_connect("localhost", "my_user", "my_password", "my_db");
To fetch the array, you would use:
while($row = mysqli_fetch_assoc($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
And finally, to close the connection:
mysqli_close($con);
Note: Just so you know, when using queries with user input, please use prepared statements and bind_param. This will prevent SQL injection attacks. I will show and example below.
$stmt = $db->prepare("SELECT * FROM users WHERE username = ?");
$username = $_POST['username'];
$stmt->bind_param('s', $username);
$result = $stmt->execute();
<?php
$con = mysqli_connect("localhost”,“my_user","my_password”,"my_db”);
//establish database connection
if (!$con)
{
die('Could not connect:'.mysqli_error());
}
$result = mysqli_query($con,"SELECT image,caption FROM tbllinkcat, tblimages WHERE tbllinkcat.catid = tblimages.catid AND tbllinkcat.catid=1");
//perform sql select query with database connection
while($row = mysqli_fetch_array($result))
{
echo $row['image'];
echo "<br />";
echo $row['caption'];
echo "<br />";
}
mysqli_close($con);
?>
For More Info read :-https://www.php.net/manual/en/mysqli.query.php
Related
I'm using PHP to try and select a single row from a table in my MySQL database. I've run the query manually inside phpMyAdmin4 and it returned the expected results. However, when I run the EXACT same query in PHP, it's returning nothing.
$query = "SELECT * FROM characters WHERE username=".$username." and charactername=".$characterName."";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
And when I test this in browser I get the "No results..." echoed back. Am I doing something wrong?
This isn't a duplicate question because I'm not asking when to use certain quotes and backticks. I'm asking for help on why my query isn't working. Quotes just happened to be incorrect, but even when corrected the problem isn't solved. Below is the edited code as well as the rest of it. I have removed my server information for obvious reasons.
<?PHP
$username = $_GET['username'];
$characterName = $_GET['characterName'];
$mysqli = new mysqli("REDACTED","REDACTED","REDACTED");
if(mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM `characters` WHERE `username`='".$username."' and `charactername`='".$characterName."'";
if($result = $mysqli->query($query))
{
while($row = $result->fetch_row())
{
echo $row[0];
}
$result->close();
}
else
echo "No results for username ".$username." for character ".$characterName.".";
$mysqli->close();
?>
It's failing: $mysqli = new mysqli("REDACTED","REDACTED","REDACTED"); because you didn't choose a database.
Connecting to a database using the MySQLi API requires 4 parameters:
http://php.net/manual/en/function.mysqli-connect.php
If your password isn't required, you still need an (empty) parameter for it.
I.e.: $mysqli = new mysqli("host","user", "", "db");
Plus, as noted.
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
Footnotes:
As stated in the original post. Strings require to be quoted in values.
You need to add quotes to the strings in your query:
$query = "SELECT *
FROM characters
WHERE username='".$username."' and charactername='".$characterName."'";
I rarely do programming. I only know enough to be dangerous as they say and I simply assemble bits of code to get what I want. My code below seems to die at the $sql query statement. It never returns any data. It should show the 13 records that are present, but it says there is none to return. I'm guessing this is some kind of syntax error?
<?php
$host = 'myipaddress';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydatabase';
$conn = mysql_connect($host, $user, $pass, $db) or die("Can not connect." . mysql_error());
// Create connection
//$conn = mysqli_connect($host, $user, $pass, $db);
// Check connection
if (!$conn) {
die("Connection failed: ");
}
$sql = "SELECT * FROM pages WHERE pid > '5'";
$result = mysql_query($conn, $sql);
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
mysql_close($conn);
?>
Your using the mysql_ API right up until you try to fetch rows here, where you're using mysqli_. That will not work.
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
Your script is at risk for SQL Injection Attacks. Please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
EDIT: Your connection (Good Eyes Ralph!) string will not work because mysql_connect() doesn't accept the database as part of the connection. You must use the additional function mysql_select_db() to choose your database.
In addition, it is not necessary to specify the connection link in mysql_query() but if you do it should be the second argument:
$result = mysql_query($sql, $conn);
There is quite a bit wrong with your code.
mysql_connect($host, $user, $pass, $db)
mysql_connect() uses 3 parameters, the 4th doesn't do what you think it does.
http://php.net/manual/en/function.mysql-connect.php
You need to use mysql_select_db() http://php.net/manual/en/function.mysql-select-db.php
Then,
$result = mysql_query($conn, $sql);
The connection comes second in mysql_.
http://php.net/manual/en/function.mysql-query.php
Then you're mixing a MySQLi function mysqli_fetch_assoc which doesn't intermix with the mysql_ library.
Read: Can I mix MySQL APIs in PHP?
So, just use the full MySQLi library
http://php.net/manual/en/book.mysqli.php
or PDO:
http://php.net/manual/en/book.pdo.php
Along with a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
Check for the real errors, should your query fail:
http://php.net/manual/en/function.mysql-error.php
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
As you can see, I did not provide you with a full rewrite, as I feel that in "Teaching a person how to fish...", will feed them for life, rather than "Throwing them a fish...", and only feed them for a day (wink).
You need to use mysql_fetch_assoc() in place of mysqli_fetch_assoc(), because your previous functions are based on mysql_*, not mysqli_*
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
So I've been learning for about 3 months now and am currently using very old procedural techniques and the deprecated mysql extension in my code. So time to take a step forward, ditch my procedural ways and get into object oriented / prepared statements...
This is very basic but I guess everyone has to learn some day. I'm trying to get retrieve and simple dataset from mysql database..
so far I have my connection:
$useri = new mysqli('localhost', 'useri', 'xxx','yyy');
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
I get no errors so I assume this works, and I have my query:
$test_query = "SELECT * FROM t";
$test_query = $useri->real_escape_string($test_query);
echo $test_query;
if($result = $useri->query($test_query)){
while($row = $useri->fetch_object($result)){
echo $row->id;
}
$result->close();
}
$useri->close();
However I get no results... so, 2 questions:
a. what am I doing wrong? and
b. anyone recommend any good tutorials apart from the php manual for this stuff?
Thanks :)
This works for one of the table i have in my db:
$useri = new mysqli('localhost', 'useri', 'xxx','yyy');
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$test_query = "SELECT * FROM t";
$test_query = $useri->real_escape_string($test_query);
if($result = $useri->query($test_query)){
while ($row = $result->fetch_object()) { //only this is changed
echo $row->id;
}
$result->close();
}else{ //check for error if query was wrong
echo $useri->error;
}
$useri->close();
make sure that you have a space after *
$test_query = "SELECT * FROM t";
check this tutorial
http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I have created a 'db.php' file where I make a connection to my db:
$db_user = 'usprojus';
$db_pass = 'xxxxxx';
$db_host = 'localhost';
// Verbinden
$dblink = mysqli_connect($db_host, $db_user, $db_pass);
// Datenbank "myproject" auswaehlen
// Entspricht "USE myproject;"
$selected = mysqli_select_db($dblink, 'myproject');
if (!$selected) {
die ('Cannot use DB : '.mysqli_error($dblink));
}
mysqli_set_charset($dblink, 'utf8');
In order to test that is working I am trying to get data from my 'users' table:
require_once('db.php');
// Get all the data from the "users" table
$result = mysql_query("SELECT * FROM users")
or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo 'user_id: '.$row['user_id'].'<br />';
echo 'date_registered: '.$row['date_registered'].'<br />';
echo 'last_login: '.$row['last_login'].'<br />';
echo 'username: '.$row['username'].'<br />';
echo 'email: '.$row['email'].'<br />';
echo 'password: '.$row['password'].'<br />';
echo 'photo: '.$row['photo'].'<br />';
echo 'description: '.$row['description'].'<br />';
echo 'notify: '.$row['notify'].'<br />';
}
But I get this error in the browser:
No database selected
For the life of me I cannot figure out where the problem lies.
Sorry, I know this is a newbie question, and it seems it has been posted here several times. But I could not figure it out.
Thank you for your time and patience.
You're mixing up mysqli_ and mysql_ functions.
I.e. mysqli_connect, mysqli_select_db, mysqli_set_charset but then mysql_query and mysql_fetch_array in your second file.
Choose one.
Perhaps you should use mysqli_query() (see php docs)
It looks like you are connecting to the database using the mysqli functions, but your query is using a mysql function.
Try switching your query to the mysqli function:
$result = mysqli_query("SELECT * FROM users")
The problem is here:
while($row = mysql_fetch_array( $result )) {
In your db.php you are connecting with the improved MySQL extension (mysqli).
But in your while loop you use the old MySQL extension.