mysql to mysqli php, just put "i"? [duplicate] - php

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 7 years ago.
i have a website that is online about 5 years. just now I noticed that i use mysql connection.
I want to change it to mysqli.
So, I have some questions.
To change mysql to mysqli I just need to put "i" after all mysql words?
query
eg
$i=mysql_query("INSERT
to
$i=mysqli_query("INSERT
num rows:
$num = mysql_num_rows($rs);
to
$num = mysqli_num_rows($rs);
string escape:
mysql_real_escape_string
to
mysqli_real_escape_string
fetch arraw
$l = mysql_fetch_array($re);
to
$l = mysqli_fetch_array($re);
is that simple? or i need to know something else?

No it's not that simple..mysqli functions usually take a second parameter...so check the syntax of whatever functions you are changing.
For instance..instead of mysql_connect("localhost", "my_user","my_password"); for mysqli you will use mysqli_connect("localhost","my_user","my_password","my_db");

This will actually guide you through: http://lv1.php.net/manual/en/class.mysqli.php
While mysql was only the procedure-style function, the new mysqli is both: the procedure-style and object-style.
You can use the object-oriented style, like:
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
or procedural style:
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}

The parameters of mysqli are reversed I.e. mysql_query($q, $dbc) becomes mysqli_query($dbc, $q). Also some functions take extra parameters, usually the connection . Php.net has a full list of all changes.
UPDATE:
//your connection script should look somthing like this.
$db_connnect = mysqli_connect('localhost','username','password','db_name');
//the page you require the connection on should look something like this.
require_once ('db_connect.php');
//a mysqli query would look something like this.
$q = "select * from user limit 12";
$r = mysqli_query("$db_connnect, $q");
while($row = mysqli_fetch_array($r)) { ... }

Related

php - MySQL Error 1040 "Too many connections"

I have this error, I have seen on several pages how to fix it, increasing the max connections variable, but I was wondering if there is any way to retry connecting 'n' number of times before throwing that error,
I am using mysqli to create my connection.
I would be very grateful for any help you could give me to get an idea of ​​how to do it if possible
update
con.php
<?php $con = new mysqli("localhost", "root", "", "grmv");
if($conexion->connect_errno) {
die ("Error: " . $con->connect_errno . "---" . $con->connect_error);
}
return $con;
?>
Products.php
<?php
include"con.php";
mysqli_query($con,"SET NAMES 'utf8'");
$result=mysqli_query($con,"select * from bio, carac where idprod=5");
while($data=mysqli_fetch_array($result)){
....
}
$conexion->close();
}
?>
More consistent way is to keep using OOP aproach, also good practice to use bind for any untrusted input, maybe not here specifically but still good practice.
$mysqli = new mysqli(
$connectionData['DB_HOST'],
$connectionData['DB_USER'],
$connectionData['DB_PASSWORD'],
$connectionData['DB_NAME']
);
$mysqli->set_charset('utf8');
$stmt = $mysqli->prepare("select * from bio, carac where idprod=?");
$stmt->bind_param('5');
$stmt->execute();
while ($result = $stmt->fetch()) {
// do stuff
}
$stmt->close();

Small section of PHP/mysql code dies. Not sure why

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";
}

Unknown database 'database_name' in MySQL with WAMPServer

I already have my database named als and I still got the error.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con = #mysql_connect($mysql_host,$mysql_user,$mysql_password) or die(mysql_error());
#mysql_select_db($mysql_db) or die(mysql_error());
?>
Not exactly an answer to your question but too long for a comment:
After establishing the database connection you could just query the existing databases via SHOW DATABASES
<?php
$mysqli = new mysqli('localhost', 'root', '');
if ($mysqli->connect_errno) {
trigger_error('query failed: '.$mysqli->connect_error, E_USER_ERROR);
}
$result = $mysqli->query('SHOW databases')
or trigger_error('connect failed: '.join(',', $mysqli->error_list), E_USER_ERROR);
foreach( $result as $row ) {
echo join(', ', $row), "<br />\r\n";
}
Does your database als show up?
Since you're using the default root account (with an empty password; you might want to look into that as well) there shouldn't be any permission related problems. So, if the database doesn't show up, it's just not there...
(almost) same script using PDO (my weapon of choice) instead of mysqli:
<?php
$pdo = new PDO('mysql:host=localhost;charset=utf8', 'root', '', array(
PDO::MYSQL_ATTR_DIRECT_QUERY => false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
foreach( $pdo->query('SHOW DATABASES', PDO::FETCH_NUM) as $row ) {
echo $row[0], "<br />\r\n";
}
There you go. The mysql_ family has been deprecated for some time. Please change to the mysqli_ library. Another machine may work because it's using an older version of PHP in which it hasn't been deprecated OR where deprecated warnings have been globally supressed.
MySQLI Connect
In the wild
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con= mysqli_connect($mysql_host,$mysql_user,$mysql_password, $mysql_db) or die("Error " . mysqli_error($con));
There's no need to arbitrarily select the database anymore. Now you can use $con as an argument to the mysqli_ family of procedural functions.
Last, but not least, never debug with the # symbol. This suppresses the error warnings from the function it precedes.

Updating mysql database with php using variables

I am having problems updating mysql with php using varables.
mysqli_query($connection, "UPDATE passwords SET used=1, time_used='{$time}'
WHERE password='{$key}'
");
I was given the error:
Warning: mysqli_query() expects parameter 1 to be mysqli, resource given in C:\wamp\www\key_check.php on line 47
any ideas why?
Thanks!
EDIT: Whole Code: http://pastebin.com/raw.php?i=W5cx8pBP
The "new mysqli" solution seems to be giving problems when trying to
$result = mysql_query("SELECT * FROM passwords", $connection);
Thanks :)
Your connection setting must look like
$connection = new mysqli($host,$username,$pass,$db);
Then execute the query using your way or by this way also
$query="UPDATE passwords SET used=1, time_used='{$time}'
WHERE password='{$key}'
";
$stmt = $connection->query($sql);
note: using prepared statements for mysqli can also possible and great. By somehow you also needed to bind parameters in there..
You have to declare $connection by creating a new mysqli object. If you fail to do so, you can check the documentation for mysqli constructor
Here's the code from the documentation.
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
if ($connection->connect_error) {
die('Connect Error (' . $connection->connect_errno . ') '
. $connection->connect_error);

mysql vs mysqli config file and queries

I need start using the mysqli extension but I'm finding all kinds of conflicting info depending on how all the info is that I'm trying to use.
For example, my header connects to a 'config.php' file that currently looks like this:
<?php
$hostname_em = "localhost";
$database_em = "test";
$username_em = "user";
$password_em = "pass";
$em = mysql_pconnect($hostname_em, $username_em, $password_em) or trigger_error(mysql_error(),E_USER_ERROR);
?>
But when I go to php.net I see that I should be using this but after updating everything I get no database.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
?>
I also went through and added an "i" to the following code in my site and again no luck:
mysql_select_db($database_em, $em);
$query_getReview =
"SELECT
reviews.title,
reviews.cover_art,
reviews.blog_entry,
reviews.rating,
reviews.published,
reviews.updated,
artists.artists_name,
contributors.contributors_name,
contributors.contributors_photo,
contributors.contributors_popup,
categories_name
FROM
reviews
JOIN artists ON artists.id = reviews.artistid
JOIN contributors ON contributors.id = reviews.contributorid
JOIN categories ON categories.id = reviews.categoryid
ORDER BY reviews.updated DESC LIMIT 3";
$getReview = mysql_query($query_getReview, $em) or die(mysql_error());
$row_getReview = mysql_fetch_assoc($getReview);
$totalRows_getReview = mysql_num_rows($getReview);
And here's the only place on my display page that even mentions mysql so far:
<?php } while ($row_getReview = mysql_fetch_assoc($getReview)); ?>
I did see something at oracle that another stackoverflow answer pointed someone to that updates this stuff automagically, but I have so little code at this point it seems like overkill.
Adding an i to any mysql function won't make it a valid mysqli function. Even if such function exists, maybe the parameteres are different. Take a look here http://php.net/manual/en/book.mysqli.php and take some time to check mysqli functions. Maybe try some examples to become familiar with the way things work. I also reccomend you to choose either object oriented code, either procedural. Don't mix them.
I just made the switch to mysqli lately, took me a few hours to wrap my head around it. It works well for me, hope it will help you out a bit.
Here the function to connect to the BD:
function sql_conn(){
$sql_host = "localhost";
$sql_user = "test";
$sql_pass = "pass";
$sql_name = "test";
$sql_conn = new mysqli($sql_host, $sql_user, $sql_pass, $sql_name);
if ($sql_conn->connect_errno) error_log ("Failed to connect to MySQL: (" . $sql_conn->connect_errno . ") " . $sql_conn->connect_error);
return $sql_conn;
}
This will return a Mysqli Object that you can use to make you request afterward. You can put it in your config.php and include it or add it at the top of your file, whatever works the best for you.
Once you have this object, you can use it to make your query against the object like so: (in this case, if an error came up it will be outputted in the error_log. I like having it there, you can echo it instead.
//Use the above function to create the mysqli object.
var $mysqli = sql_conn();
//Create the query string (truncated for the example)
var $query = "SELECT reviews.titl ... ... ted DESC LIMIT 3";
//Launch the query on the mysqli object using the query() method
if(!($results = $mysqli->query($query))){
//It it fails, log the error
error_log(mysqli_error($mysqli));
}else{
//Manipulate your data.
//here it depends on what you retunr, a single value, row or a list of rows.
//Example for a set of rows
while ($record = $results->fetch_object()){
array_push($array, $record);
}
}
//Just to show, this will output the array:
print_r($array);
//Close the connection:
$mysqli->close();
So basically, in mysqli, you create an object and use the method to work your way out.
Hope this helps. Once you figured it out, you will most likely enjoy mysqli more that mysql. I did anyway.
PS: Please note that this was copy/pasted from existing, working code. Might have some typo, and might forgot to change a var somewhere, but it's to give you an idea of how mysqli works. Hope this helps.

Categories