conversion of mysql to msqli - php

Mysql is deprecated. I have a code in mysql that I would like to convert to mysqli, but I don't succeed.
The code works, but I have error messages "The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead"
Here is the initial code:
$connection = mysql_connect('host','root','password') or die ("Couldn't connect to server.");
$db = mysql_select_db('database_name', $connection) or die ("Couldn't select database.");
$result = mysql_query("SELECT * FROM customers WHERE cust_number ='$Cust_Number' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE `customers` SET cust_name='$Cust_Name', cust_phone='$Cust_Phone', cust_phone1='$Cust_Phone1', cust_email='$Cust_Email', cust_address='$Cust_Address' ");
}
else
{
mysql_query("INSERT INTO customers (cust_number, cust_name, cust_phone, cust_phone1, cust_email, cust_address) VALUES ('$Cust_Number', '$Cust_Name', '$Cust_Phone', '$Cust_Phone1', '$Cust_Email', '$Cust_Address') ");
}
I tried the following conversion:
$connection = mysqli_connect('host','root','password') or die ("Couldn't connect to server.");
$db = mysqli_select_db($connection,'database_name') or die ("Couldn't select database.");
if( mysqli_num_rows($result) > 0) {
mysqli_query($connections,"UPDATE `customers` SET cust_name='$Cust_Name', cust_phone='$Cust_Phone', cust_phone1='$Cust_Phone1', cust_email='$Cust_Email', cust_address='$Cust_Address' ");
}
else
{
mysqli_query($connections,"INSERT INTO customers (cust_number, cust_name, cust_phone, cust_phone1, cust_email, cust_address) VALUES ('$Cust_Number', '$Cust_Name', '$Cust_Phone', '$Cust_Phone1', '$Cust_Email', '$Cust_Address') ");
}
But it doesn't work.
Can someone help me convert the initial code in mysqli or PDO?

Your mysqli_query() calls $connections, whereas your connection is $connection -- this is why your code is failing.
It is, however, worth noting that as it stands, your code is vulnerable to SQL injection. To avoid this, you'll want to make use of prepared statements (something which didn't exist with the MySQL connector).
This can be done with the following:
$connection = mysqli_connect('host','root','password') or die ("Couldn't connect to server.");
$db = mysqli_select_db($connection,'database_name') or die ("Couldn't select database.");
if (mysqli_num_rows($result) > 0) {
$stmt = $this->mysqli->prepare("UPDATE `customers` SET cust_name='?', cust_phone='?', cust_phone1='?', cust_email='?', cust_address='?'");
$stmt->bind_param('sssss', $Cust_Name, $Cust_Phone, $Cust_Phone1, $Cust_Email, $Cust_Address);
$stmt->execute();
}
else
{
$stmt = $this->mysqli->prepare("INSERT INTO customers (cust_number, cust_name, cust_phone, cust_phone1, cust_email, cust_address) VALUES ('?', '?', '?', '?', '?', '?') ");
$stmt->bind_param('ssssss', $Cust_Number, $Cust_Name, $Cust_Phone, $Cust_Phone1, $Cust_Email, $Cust_Address);
$stmt->execute();
}

Related

PHP mysql_query inside FOR only works first loop

I´m trying to update some different registers in a mysql database sending the commands from a FOR loop in php, but the query is only done the 1st loop. Here´s the code:
$conexion = mysql_connect($hostname, $user, $pass) or die ("Error establishing connection with the Database");
mysql_select_db($db,$conexion) or die("Error selecting the Database");
$j=0;
for ($i=0;$i<count($notifs);$i++){
$sql="UPDATE tef SET notif='$notifs[$i]' WHERE sn_rec='$unsersn_recs[$j]';";
echo $sql."<br>";
$res=mysql_query($sql, $conexion) or die (mysql_error());
$j++;
}
mysql_close($conexion);
The query text is correctly done (the echo shows the different lines created), but the changes in the database are done only in the 1st loop (1st query) and I don´t receive any error. What may I be missing?
Thanks in advance!
This is wonderful example where you should use prepared statements.
I give you an example which is also secure against SQL injections.
$mysqli = new mysqli($hostname, $user, $pass, $db);
if (mysqli_connect_errno()) {
die("Error establishing connection!");
}
$stmt = $mysqli->prepare("UPDATE tef SET notif=? WHERE sn_rec=?");
$j=0;
for ($i=0;$i<count($notifs);$i++) {
$stmt->bind_param('ii', $notifs[$i], $unsersn_recs[$j]);
$stmt->execute();
if(!empty($stmt->error)) echo $stmt->error;
$j++;
}
$stmt->close();
$mysqli->close();
Hint: If notif or sn_rec are varchar/text types, just replace the 'i' with a 's' in bind_param().

error in mysql_fetch_assoc();

I keep having an error in mysql_fetch_(assoc,array,row) I can't find the problem and when I try to count the rows of the result by using echo the result is 1
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in C:\wamp\www\Jocales\login.php on line 88
in query SELECT * FROM users WHERE uName ='nuha' AND uPassword = '123'
<?php
$login= $_POST['login'];
$password= $_POST['password'];
if($login && $password){
$con = mysql_connect("localhost", "root", "")or die ('no connection');
mysql_select_db("jocales",$con) or die ('no');
$query= "SELECT * FROM users WHERE uName ='$login' AND uPassword = '$password'";
$result = mysql_query($query)or die(mysql_error()." in query $query");
$record=mysql_fetch_assoc($query) or die(mysql_error()." in query $query");
?>
Change
$record=mysql_fetch_assoc($query)
To
$record=mysql_fetch_assoc($result)
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
WARNING: You code is vulnerable to SQL Injection.
use this code ( replace $query with $result )
<?php
$login= $_POST['login'];
$password= $_POST['password'];
if($login && $password){
$con = mysql_connect("localhost", "root", "")or die ('no connection');
mysql_select_db("jocales",$con) or die ('no');
$query= "SELECT * FROM users WHERE uName ='$login' AND uPassword = '$password'";
$result = mysql_query($query)or die(mysql_error()." in query $query");
$record=mysql_fetch_assoc($result) or die(mysql_error()." in query $query");
?>
The function mysql_fetch_assoc() expects one parameter and it should be a resource type. You're providing a string.
$query= "SELECT * FROM users WHERE uName ='$login' AND uPassword = '$password'";
$result = mysql_query($query)or die(mysql_error()." in query $query");
//this is the issue!
$record = mysql_fetch_assoc($query) or die(mysql_error()." in query $query");
the last statement should be
$record = mysql_fetch_assoc($result) or die(mysql_error()." in query $query");
NOTE (straight from php.net about mysql_*)
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.

how to use php variables in postgresql query

I have two php variables, one integer and other json, which I convert into string variable and then inserting them inside a postgresql database.
Converting integer into string variable:
$string1 = (string)$integer;
Coneverting json from facebook api into string variable:
$string2 = json_encode($json);
Now, I have to insert these two string variables into postgres database:
$query = "INSERT INTO interests VALUES(". $string1 ." ," . $string2 .")";
pg_query($con, $query) or die("Cannot execute query: $query\n");
This is not working. I have tried a lot of solutions but still not working.
I changed my function to insert into database
function push_interests(){
$id = $facebook->getUser();
$int = $facebook->api('/me/interests');
$host = "hostname";
$user = "user";
$pass = "password";
$db = "database";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$id = (string)$id;
$int = json_encode($int);
$sql = "INSERT INTO interests VALUES($1,$2)";
pg_prepare($con,'my_insert', $sql) or die ("Cannot prepare statement1\n") ;
pg_execute($con,'my_insert', array($id,$int)) or die ("Cannot execute statement1\n");
pg_close($con);
}
Output is: cannot execute statement1
I have created database as below:
$query = "DROP TABLE IF EXISTS interests";
pg_query($con, $query) or die("Cannot execute query: $query\n");
$query = "CREATE TABLE interests(id VARCHAR(25) PRIMARY KEY, interests VARCHAR(500))";
pg_query($con, $query) or die("Cannot execute query: $query\n");
Because strings need to be surrounded with simple quotes. I would strongly advise you use prepared statements to ignore these kind of problems and ensure correct variable escaping to prevent your application from beeing hacked trough SQL injection.
$sql = "INSERT INTO interests VALUES ($1, $2)";
$result = pg_prepare($con, 'my_insert', $sql);
$result = pg_execute($con, 'my_insert', array($string1, $string2));
See http://php.net/manual/en/function.pg-prepare.php
Edit: Here is the actual code I've tested:
<?php
$con = pg_connect('')
or die ("Could not connect to server\n");
$id = (string) 5;
$int = json_encode(array('pika' => 'chu', 'plop' => array(1, 2, 3)));
$query = "CREATE TABLE interests(id VARCHAR(25) PRIMARY KEY, interests VARCHAR(500))";
pg_query($query) or die('creating table failed.');
$sql = "INSERT INTO interests (id, interests) VALUES ($1, $2)";
pg_prepare('my_query', $sql);
pg_execute('my_query', array($id, $int)) or die("Error while inserting.");

How to insert data into mysql database using oops php5 concepts?

I am new for PHP5 OOP concept.
Please give some example source code for "How to insert data using oops concept?".I want to use pure php5 concept for this even in the connection.php page also.
I want to improve my knowledge. please any one help me....
I know below the basic concept
insert_db.php
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
connectio.php
<?php
// connect database code
$dbhost ='localhost';
$dbuser = 'tomking';
$dbpass = 'dsfds';
$dbname = 'mydb';
//connectivity of database
$conn = mysql_connect($dbhost,$dbuser,$dbpass) or die ('Error Connecting to mysql');
mysql_select_db($dbname);
?>
Use Mysqli or PDO for using sql queries instead of directly pass variables to query.
This will cause sql injection when you directly pass variable to query
If you want to pass variable to sql query , you have to use filters for this
filtering-escaping-post-data-from-injection-attacks
PDO Documentation
MySQLi Documentation
And this is all pure PHP5 concept.
$mysqli = new mysqli($hostname, $username, $password, $database_name);
if($mysqli->error)
die($mysqli->error);
$mysqli->query("SET NAMES 'UTF8'");
$query = "INSERT INTO my_table VALUES ('value_1', 'value_2')";
$mysqli->query($query);
if(!$mysql->error)
echo 'do something';
$query = "SELECT * FROM my_table";
$sql = $mysqli->query($query);
if($sql->num_rows > 0) {
while($row = $sql->fetch_assoc()) {
echo $row['field_1'];
}
}
$sql->close();

Problem logging in with PHP's $SETTINGS

I'm trying to get the user's login details from the database using $SETTINGS["admin_username"] and also the password. I have defined them as 'user' (for username) and pass (for password), and I want them to be pulled from database table userLogin.
Any ideas? Please help, I have tried everything but the page either doesn't open or it doesn't work at all.
<?php
error_reporting(0);
$SETTINGS["admin_username"]='user';
$SETTINGS["admin_password"]='pass';
$SETTINGS["mysql_user"]='user';
$SETTINGS["mysql_pass"]='pass';
$SETTINGS["hostname"]='localhost';
$SETTINGS["mysql_database"]='db_db';
$connection = mysql_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"]) or die ('request "Unable to connect to MySQL server."'.mysql_error());
$db = mysql_select_db($SETTINGS["mysql_databas… $connection) or die ('request "Unable to select database."');
?>
I can't read your code, so I try to write it again, here:
<?php
error_reporting(0);
$SETTINGS["admin_username"]='user';
$SETTINGS["admin_password"]='pass';
$SETTINGS["mysql_user"]='user';
$SETTINGS["mysql_pass"]='pass';
$SETTINGS["hostname"]='localhost';
$SETTINGS["mysql_database"]='db_db';
$connection = mysql_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"]) or die ('request "Unable to connect to MySQL server."'.mysql_error());
$db = mysql_select_db($SETTINGS["mysql_database", $connection) or die ('request "Unable to select database."');
$sql = "SELECT * FROM userLogin LIMIT 1";
$rs = mysql_query($sql, $connection) or die(__LINE__.":".mysql_error());
while(false !== ($r = mysql_fetch_assoc($rs)))
{
$SETTINGS["admin_username"]=$r['field_user'];
$SETTINGS["admin_password"]=$r['field_pass'];
}
?>
Notice this line:
$sql = "SELECT * FROM userLogin LIMIT 1";
I use this in assumption that you only have 1 entry on table userLogin. If it's not, maybe you can use the following alternative query (because I don't know your current table's schema):
$sql = "SELECT * FROM userLogin WHERE field_user = 'admin'";
For starters, you've got an error in your syntax, Line 12 (and so does silent in his reproduction):
$db = mysql_select_db($SETTINGS["mysql_databas… $connection) or die ('request "Unable to select database."');
I'm guessing you want
$db = mysql_select_db($SETTINGS["mysql_database"], $connection) or die ('request "Unable to select database."');

Categories