MySQL unwanted automatic replacing \n to linebreaks when storing data - php

I am using PHP to pass a query like this:
"UPDATE `prove750_mrdias`.`stringsMrDias`
SET `conteudo` = '$conteudo'
WHERE `stringsMrDias`.`ID` = $id;"
when I echo $conteudo I get Sobre\nmim as expected.
But after the query, I look at the database and the value stored is the formatted string:
'sobre
mim'
That's causing all sorts of problems when parsing the data back to my application.
If I go to phpMyAdmin and pass the value of $conteudo manually it maintains the expected behavior, only when querying the replace is happening without calling it.
Any ideas?

I suspect it's an issue of interpolation. You can kill two birds with one stone by using prepared statements. By using prepared statements
your data won't be corrupted or need to be manually handled by you,
your application will not be subject to security issues a la SQL injection.
This might look like:
$sql = "UPDATE `prove750_mrdias`.`stringsMrDias` SET `conteudo` = ? WHERE `stringsMrDias`.`ID` = ?";
$preparedStatement = $pdo_handle->prepare( $sql );
$preparedStatement->execute([$conteudo, $id]);
That is, you first tell the database the form of the query you want executed, and then -- in a separate call -- you send the arguments to that query.

Try http://php.net/manual/en/function.nl2br.php
Example,
$conteudo = nl2br($conteudo);
Then store into database.

Prepared statements was the right direction.
After looking at the mysqli documentation I ended up with a code like this:
`$sql = "UPDATE `prove750_mrdias`.`stringsMrDias` SET `conteudo` = (?) WHERE `stringsMrDias`.`ID` = (?)";
if (!($stmt = $con->prepare($sql))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param('ss', $conteudo,$id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}`
Had to use the bind_param() as execute() don't accept any parameters.

Related

PHP code for inserting non-duplicate values into MySQL

I have basic PHP/MySQL experience, having taken an introductory class. My knowledge is literally limited to the following PHP codes:
if(!($stmt = $mysqli->prepare...)
if(!($stmt->bind_param...)
if(!$stmt->execute...)
I'm currently trying to write a program that allows a user to enter a new password, and checks the password against existing passwords in the database.
Here is what I have:
<?php
foreach($Password){
$dupesql = "SELECT PasswordID Passwords WHERE (Password = '$Password')";
$duperaw = mysql_query($dupesql);
if(mysql_num_rows($duperaw){
echo nl2br("$Password has already been used \n");
}
else{
echo "Password added \n";
}
}
?>
I got the code from this post: Check for duplicates before inserting
I'm not sure if the code itself has problems or if I need to add anything else to my PHP code to get this working, as it's currently producing an "Error 500".
MySQL extension is deprecated and probably you have PHP 7.0 from where it is removed. Rewrite your code to MySQLi or PDO. Check this question on how to convert to MySQLi: How could I change this mysql to mysqli?
Also, your code just doesn't add a password (never). Probably you expect to add it before the "Password Added" message, but be aware: the solution you want to use is not ideal, because there is a risk of race condition between checking the password for existence and adding it. This means that it is possible to add a password twice.
To solve this problem, you might want to use transactions. More details are covered in this question: PHP + MySQL transactions examples
I decided to go an entirely different route, which is to set the Password column as unique.
Then I did a simple INSERT that would prompt an error if the user attempts to add a duplicate:
<?php
if(!($stmt = $mysqli->prepare("INSERT INTO Heroes(HeroName, FirstName, LastName, Age, HomeCountry, RoleID) VALUES (?,?,?,?,?,?)"))){
echo "Prepare failed: " . $stmt->errno . " " . $stmt->error;
}
if(!($stmt->bind_param("sssisi",$_POST['HeroName'],$_POST['FirstName'],$_POST['LastName'],$_POST['Age'],$_POST['HomeCountry'],$_POST['RoleID']))){
echo "Bind failed: " . $stmt->errno . " " . $stmt->error;
}
if(!$stmt->execute()){
echo "Execute failed: " . $stmt->errno . " " . $stmt->error;
} else {
echo "Added " . $stmt->affected_rows . " row to Heroes.";
}
?>

PHP doesn't send data to MySQL

Have some problem I couldn't find solution for, though searched through many sources (and questions here too). So, here it is.
With the PHP-code below I suppose to collect data from a HTML-form and send it to a local WAMP-server. But, though final check shows me "Success!", no new rows in the database's table are found, it stays empty. Names are correct, commands are (as I see it) too, so I just don't know what's wrong.
I hope you guys could help me. ^^
//Check if user submited a form
if (isset($_POST['submit'])) {
//Check if from is properly filled
if (empty($_POST['itemName']) || empty($_POST['itemPic']) || empty($_POST['itemPrice']) || empty($_POST['itemProvider'])) {
echo '<script>alert ("Fill out the form please!")</script>';
} else {
$conn = new mysqli('localhost:3306', 'root', '', 'goods-review');
//Check if connection established
if (mysqli_connect_errno()) {
exit('Connect failed: ' . mysqli_connect_error());
}
//Sending data
$newItem = array('itemName' => $_POST['itemName'], 'itemPic' => $_POST['itemPic'], 'itemPrice' => $_POST['itemPrice'], 'itemProvider' => $_POST['itemProvider']);
$sql = "INSERT INTO goods (itemName, itemPic, itemPrice, itemDate, itemProvider) VALUES ('" . $newItem['itemName'] . "', '" . $newItem['itemPic'] . "', '" . $newItem['itemPrice'] . "', date('Y:m:d, H:i:s'), '" . $newItem['itemProvider'] . "')";
//Check if sent
if ($sql) {
echo '<script>alert ("Success!")</script>';
} else {
echo '<script>alert ("Error!")</script>';
}
$conn->close();
}
}
The code is just assigning a string value to a variable.
$sql = "INSERT ...";
And the string value is not submitted to the database; it's not being executed as a SQL statement. There's nothing magical about the name of the variable. As far as PHP is concerned, the code is just assigning a value to a variable. That's it.
If you want to execute a SQL statement, you need to add code that actually does that. It shouldn't be difficult to find an example of how to do that.
IMPORTANT NOTE: The code in the question appears to create a SQL statement that is vulnerable to SQL Injection. A much better pattern is to use prepared statements with bind placeholders.
Reference: mysqli_prepare
If there's some (unfathomable) reason that you can't use prepared statements, then at a minimum, any potentially unsafe values that are included in the SQL text must be properly escaped.
Reference: mysqli_escape_string
If you have setup the $newItem array first.
Normaly you will validate the user-input and ensure that the user-input has no SQL injections in it.
Read here about it: What is SQL injection?
After that
(You have to add $newItem['itemDate']=date('Y:m:d, H:i:s');)
$sql = "INSERT INTO goods (".implode(', ',array_keys($newItem)).")"
." VALUES ('".implode("', '",$newItem)."')";
if (mysqli_query($conn,$sql)){
echo '<script>alert ("Success!")</script>';
} else {
echo '<script>alert ("Error!")</script>';
}
If you are using this:
you dont have too keep an eye on the right field order
every field value becomes ' around them
you have less code to write
field count and order can change
Finally mysqli_query() returns FALSE if nothing is insert and you can check for that.
Sidenote: Try to use OOP Version of the MYSQLi Extention and Prepared Statments. Read about it here: mysqli, OOP vs Procedural

posting data with apostrophe

I'm a complete beginner at PHP but have managed a simple code to input data to a table.
The code is:
$query = "INSERT into $table (suggestion1) VALUES('$suggestion1')";
All works fine but if the data inserted contains an apostrophe (e.g. don't) the query fails.
I've searched for hours but the answers I get are beyond my knowledge.
Any help or pointers would be great!
Steven
What you should be looking are prepared statements, in which to write your queries with parameters, and the call that prepared statement passing in parameters values and let the driver make the replaces/escaping. Here's a good starting point using mysqli.
Here's a simplified code sample from PHP.net :
$mysqli = new mysqli("example.com", "user", "password", "database");
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
You want to escape your input: check the documentation.
Basically, what happens is this: when you put that data in with quotes, you get this:
INSERT INTO $table (suggestion1) VALUES ('it's great');
and MySQL gets confused with the second quote. When you "escape" you get this:
INSERT INTO $table (suggestion1) VALUES ('it\'s great');
and MySQL knows that second quote is part of the data, not of the query.
Wikipedia has info on it as well (a little more extensive, but worth reading and understanding).

PHP attempt to update a MySQL database doesn't update anything

I have my code below to update a my MySQL database, it's running but is not updating the database when I check rcords using phpmyadmin. plae hlp me.
$database = "carzilla";
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$manufacturerTable = $_POST[vehicleManufacturer];
$numberToSearch = $_POST[vehicleIdNo];
$engineType = $_POST[engineType];
$engineCC = $_POST[engineCC];
$year = $_POST[year];
$numberofDoors = $_POST[numberofDoors];
$tireSize = $_POST[tireSize];
$chasisNumber = $_POST[chasisNumber];
$vehicleMake = $_POST[vehicleMake];
$price=$_POST[price];
mysql_select_db("$database", $con);
$sql = mysql_query("UPDATE $manufacturerTable SET username='vehicleMake',
engineType='$engineType', engineCC='$engineCC', year='$year', chasisNo='$chasisNumber', numberOfDoors='$numberofDoors' ,numberOfDoors='$numberofDoors', tireSize='$tireSize', price='$price' WHERE `index` ='$id'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo 'record has been successfuly';
mysql_close($con);
?>
Take a good look at your query. You are referring to PHP variables in several different fashions in the same statement. In the query $manufacturerTable is just $manufacturerTable, you encase a few others in single quotes, some of which you remove the $ from, others you do not. I know I preach this far too often, but you should really look into using prepared statements. They take all the guess work out of using variables in your queries, and they prevent you from being victimized by injection hacks. But the short answer here is that you are not referencing your variables correctly in the query.
Sometimes putting the variables directly in the syntax can cause issues. Have you tried to use concatenation for the query.
$query = "UPDATE ".$manufacturerTable." SET username='vehicleMake', engineType='."$engineType."', engineCC='".$engineCC."', year='".$year."', chasisNo='".$chasisNumber."', numberOfDoors='".$numberofDoors."' ,numberOfDoors='".$numberofDoors."', tireSize='".$tireSize."', price='".$price."' WHERE index =".$id;
$sql = mysql_query($query); # this should be put in the if else
If index is number based you do not need the '' surrounding it. Plus is username='vehicleMake' or is it a variable. if it is a variable, add the $ or use concatenation like the rest. Your SQL check should be something like follows.
if (mysql_query($query))
{
echo 'record has been successfuly';
} else {
die('Error: ' . mysql_error() . ' | ' . $query);
}
The reason you export the query is so you can try it manually to make sure it works and what error you may be getting. phpMySQL can show a different error then the mysql_error() at times
Plus you should be escaping all input that is user entered using mysql_escape_string() or mysql_real_escape_string()

Why is PHP mysqli prepared statement working but inserting all NULL values?

What would cause this? Code follows:
$m = new mysqli($host,$user,$pass,$db);
if(mysqli_connect_errno()) die('Connect failed: ' . mysqli_connect_error());
$PrepSQL = "INSERT INTO Products (" . implode(',',$this->cols) . ") VALUES (";
$PrepSQL .= '?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$stmt = $m->prepare($PrepSQL);
if(!$stmt) die('Could not prepare: ' . $m->error . "\n$PrepSQL\n");
$ret = $stmt->bind_param('isissssddssssssssssssssssssssssssisssssss',
$contents[0], ... bunch of these here ... );
if(!$ret) die('bind_param failed: ' . $m->error);
Then in a loop I have:
$contents = explode('|',$NL); // NL is pipe delimited data
print_r($contents);
if(!$stmt->execute()) die("Statement failed: " . $m->error);
And the script doesn't halt but every value is null in MySQL. Most of the types are strings and I would assume they would at least fill in even if the numeric types are wrong. The print_r is printing values correctly.
Can you show the complete code from preparing the statement to executing it?
I suspect that $contents in the first part is not the same $contents as in the second part. They need to be references to the same array, since you're populating it after binding it by reference.

Categories