How to upgrade from mysql_* to mysqli_*? - php

I'm currently using deprecated code to get data from users, as follows:
/* retrieve */
$lastName = $_POST['lastName'];
$firstName = $_POST['firstName'];
$examLevel=$_POST['level'];
/* connect */
$dbc=mysql_connect("localhost", "user", "passw") or die('Error connecting to MySQL server');
mysql_select_db("db") or die('Error selecting database.');
/* sanitize */
$lastName=mysql_real_escape_string($lastName);
$firstName=mysql_real_escape_string($firstName);
$examLevel=mysql_real_escape_string($examLevel);
/* insert */
$query_personal = "INSERT INTO personal (LastName, FirstName) VALUES ('$lastName', '$firstName')";
$query_exam = "INSERT INTO exam (Level, Centre, BackupCentre, etc.) VALUES ('$examLevel', '$centre', '$backup', 'etc')";
This is working but I keep coming across warnings about security and lack of support. There's a small rewrite to connect with mysqli instead of mysql but what about mysqli_real_escape_string? I've seen it used in examples but I've also seen advice to use prepared statements instead which don't use mysqli_real_escape_string.
And how would I use prepared statements to INSERT my data? I'm a bit at sea with this bit so far. For example, is parameter binding only for INSERTs and result binding only for SELECTs?

Convert it to PDO
/* connect */
$dsn = "mysql:host=localhost;db=test;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,"user", "passw", $opt);
/* insert */
$query = "INSERT INTO personal (LastName, FirstName) VALUES (?, ?)";
$stmt = $pdo->prepare($query);
$stmt->execute(array($_POST['lastName'],$_POST['firstName']));
$query = "INSERT INTO exam (Level, Centre, BackupCentre, etc) VALUES (?, ?, ?, 'etc')";
$stmt = $pdo->prepare($query);
$stmt->execute(array($_POST['level'], $centre, $backup));

see this pages for converting mysql into mysqli
Converting_to_MySQLi
https://wikis.oracle.com/display/mysql/Converting+to+MySQLi
and see mysqli_real_escape_string manual that explain about mysqli_real_escape_string and Security problem and how to solve it.
php.net:
Security: the default character set
The character set must be set either at the server level, or with the API function mysqli_set_charset() for it to affect mysqli_real_escape_string(). See the concepts section on character sets for more information.
see this page for query for insert data
see this page for prepare data for inserting to mysql
and http://php.net/manual/de/mysqli.quickstart.prepared-statements.php

Related

Inserting latin chars in mysql using php?

I have a database that contains latin chars like á, é, ç etc. I can insert tuples with those chars using the MySQL admin interface by writing the SQL insert statements there. I can also read and display them without any problem. But I can't insert new data properly using PHP.
$mysqli = new mysqli("localhost", "root", "", "budgets");
$data = mysqli_real_escape_string($mysqli, "bananá");
$stmt = $mysqli->prepare("INSERT INTO items(id_budget, description, unit_price, quantity) VALUES (1, ?, 3, 3);");
$stmt->bind_param("s", $data);
$stmt->execute();
I have read several threads suggesting to use mysqli_real_escape_string(), and making sure the charsets were configured properly, but nothing worked.
I tried using different charsets in the database but the á is always replaced by strange symbols. Currently I'm using utf8_general_ci as the charset of the database.
Thank you in advance for any assistance.
First thing setup your table rows collcation to utf8_unicode_c
And add $mysqli->set_charset("utf8"); to your connection code
Finaly your code should look like this :
$mysqli = mysqli_connect(HOST_NAME,DB_USER,DB_PASS,DB_NAME);
if($mysqli === false) {
die("Something was wrong ! Please try again later."); // Error if connection not ok.
}
$mysqli->set_charset("utf8");
$data = "bananá";
$stmt = $mysqli->prepare("INSERT INTO items(id_budget, description, unit_price, quantity) VALUES (1, ?, 3, 3);");
$stmt->bind_param("s", $data);
$stmt->execute();
$stmt->close();
$mysqli->close();

Inserting variables in database in php + mysql

I'm totally PHP beginner, and I'm trying to insert variables in a database in PHP and MySQL.
This is my code:
$link = mysql_connect('localhost','','','onlynews') or die('Cannot connect to the DB');
mysql_select_db('TEST',$link) or die('Cannot select the DB');
$strSQL = "INSERT INTO news(id, title,photo,url,source, at) VALUES('$x','$title','$url','$imgurl ','$source','$at')";
mysql_query($strSQL) or die(mysql_error());
The problem is it is doing: NOTHING! No Entries at all, Nothing changes in the database.
-How can I fix this?
-Do I have to write codes to prevent SQL Injection, even if the variables are coming from an API, not from users?
You have to execute your query using $conn->query($sql);.
However, to avoid SQL injections you should definitely use prepared statements or at least $conn->real_escape_string() to escape the values in your SQL statement.
For example, this is your code using prepared statements:
$servername = "localhost";
$username = "";
$password = "";
$dbname = "onlynews";
$tableName = "news";
$conn = new mysqli($servername, $username, $password, $dbname);
$stmt = $conn->prepare("INSERT INTO news (id, title, photo, url, source, at)
VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param('ssssss', $thetitle, $urlToImage, $theurl, $thesource, $thetime);
$stmt->execute();
$stmt->close();
You should also add some error checking, since $conn->prepare() and $stmt->execute() may fail (and return false). Of course, establishing the connection to the database during the construction of $conn could also fail, which can be checked using $conn->connect_error.

Mysqli multi query in foreach loop

I have to do a lot of insert in my DB, importing data from xml.
Now, if I open and close the connection in the loop, the script works but crashes for max connection number, and if I use the following code, it execute just one time the mysqli_multi_query.
I just need to know, how to maintain the connection to execute a new multi query in the loop.
$xml = simplexml_load_file('demo.xml');
$mysqli =new mysqli($servername, $username, $password, $dbname);
foreach($xml->datas as $data) {
$sql="INSERT IGNORE INTO table1 (hobby) values ('".$data->child74."');";
$sql.="INSERT IGNORE INTO table2 (pizza, spaghetti) values ('".$data->child55."', '".$data->child52."');";
// a lot more insert...
mysqli_multi_query($mysqli,$sql);
}
mysqli_close($mysqli);
For the multiple inserts you should be using prepared statements. This approach will solve all the problems you have at once. The only possible issue (related to possible non-optimal database settings) is solved by using a transaction.
The code below is using only single connection and as fast as it can be
$xml = simplexml_load_file('demo.xml');
$stmt1 = $mysqli->prepare("INSERT IGNORE INTO table1 (hobby) values (?)");
$stmt1->bind_param("s",$hobby);
$stmt2 = $mysqli->prepare("INSERT IGNORE INTO table2 (pizza, spaghetti) values (?,?)");
$stmt2->bind_param("ss", $pizza, $spaghetti);
$mysqli->autocommit(FALSE);
foreach($xml->order as $data) {
$hobby = $data->child74;
$pizza = $data->child55;
$spaghetti = $data->child52;
$stmt1->execute();
$stmt2->execute();
}
$mysqli->commit();
$mysqli->close();
Prepared statements with a transaction make it civilized, secure and efficient solution.

MySQLi insert, successful database connection but not successfully inserted [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I'm attempting to insert some data into a table using mysqli functions.
My connection works fine using the following:
function connectDB(){
// configuration
$dbuser = "root";
$dbpass = "";
// Create connection
$con=mysqli_connect("localhost",$dbuser,$dbpass,"my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}else{
echo '<br />successfully connected<br />';
return $con;
}
}
But when I attempt to run my insert function I get nothing in the database.
function newUserInsertDB($name,$email,$password){
$con = connectDB();
// Prepare password
$password = hashEncrypt($password);
echo $password . "<br />";
// Perform queries
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ($name,$email,$password,0)");
// insert
mysqli_close($con);
}
I have been looking through the list of mysqli functions for the correct way to give errors but they all seem to be regarding the connection to the DB, not regarding success of an insert (and I can clearly see in my DB that it is not inserting.)
What would be the best way to debug? Which error handling shall I use for my insert?
I've tried using mysqli_sqlstate which gives a response of 42000 but I cannot see any syntax errors in my statement.
As mentioned in my comment, you would be better off using a prepared statement. For example...
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
$stmt->execute();
Using this, you don't have to worry about escaping values or providing quotes for string types.
All in all, prepared statements are much easier and much safer than attempting to interpolate values into an SQL string.
I'd also advise you to pass the $con variable into your function instead of creating it within. For example...
function newUserInsertDB(mysqli $con, $name, $email, $password) {
// Prepare password
$password = hashEncrypt($password);
// functions that "echo" can cause unwanted side effects
//echo $password . "<br />";
// Perform queries
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
return $stmt->execute(); // returns TRUE or FALSE based on the success of the query
}
The quotes are missing from the mysql statement from around the values. Also, you should escape the values before inserting them into the query. Do this way:
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ('".
mysqli_real_escape_string($con,$name)."','".
mysqli_real_escape_string($con,$email)."','".
mysqli_real_escape_string($con,$password)."',0)");
Regards

How can I get PDO bindValue/bindParam to bind with MySQL?

I've been using mysql and mysqli in the past, but am starting a new project, so wanted to go back to OOP with PDO-mysql .. however, it doesn't want to work:
$dbh = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
if(isset($_POST["name"]) && isset($_POST["password"]))
{
$pwdHasher = new PasswordHash(8, FALSE);
$hash = $pwdHasher->HashPassword($_POST["password"]);
//$insert = $dbh->prepare('insert into users (username,password) values ("?","?")');
$insert = $pdo->prepare("insert into users (username,password) values (?,?)");
$insert->bindParam(1,$_POST["name"]);
$insert->bindParam(2,$hash);
$insert->execute();
echo "Registration Success!";
}
edit: The above code works if I change the code from the commented line to the non-commented (i.e. single quote to double quotes) However, this doesn't work later:
$query = $pdo->prepare("select * from users where username = ?");
$query->bindParam(1,$_POST["name"]);
$result = $query->execute()
Ok, you've found the answer to your first question.
For the second one it would be
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
called right after connect.
it will tell you what's going wrong with your query.
error_reporting(E_ALL);
also always helps with such errors like misspelled variables ($pdo is not $dbh for example)
If you want to use ? for placeholders, you are supposed to send an array to the execute-method matching the positions of the question marks. $insert->execute(array('value1', 'value2'));
You could however use named placeholders .. WHERE x = :myxvalue and use $insert->bindValue(':myxvalue', 'thevalue', PDO::PARAM_STR);
Also, please have a look at the difference between bindParam and bindValue
The answer to this question is simple and embarrassing:
I need to change the single quotes surrounding the sql statement being prepared to double quotes (and remove the double quotes where the '?' mark is.
change:
$insert = $dbh->prepare('insert into users (username,password) values ("?","?")');
to
$insert = $dbh->prepare("insert into users (username,password) values (?,?)");
and everything works.

Categories