Sometimes it sucks when you have these ; " ' (semicolon, single and double quotation marks) everything in a string.
Question is simple what is the easiest way to send those sting into the database.
base64_encode();
base64_decode();
// Is not an option. I need to keep those data just same as it is.
You need
addslashes('your text') // in your php page
PDO statements is the best solution to your problem of executing SQL queries to your database with values that have single/double quotation marks... but more importantly PDO statements help prevent SQL injection.
To show you how this works, this very simple example gives you a basic understanding of how PDO statements work. All this example does is make the connection to the database and insert the username, email and password to the users table.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$hashed_password = password_hash($password, DEFAULT_BCRYPT);
//Validation on inputs here...
// Your SQL query... here is a sample one.
$query = "INSERT INTO users (userName, email, password) VALUES (:userName, :email, :password)";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("userName" => $username, "email" => $email, "password" => $hashed_password);
$statement->execute($statementInputs);
$statement->closeCursor();
?>
You could put the establishing connection part in a separate file and require_once that file to avoid having to write the same code, again and again to establish a connection to your database.
Use mysqli_real_escape_string
$someText = mysqli_real_escape_string($con,"It's a test.");
where $con is your database connection variable.
Related
I'm trying to convert some php code that uses mysql into mysqli code. I'm not sure why it doesn't work - I didn't write the original code and am not that comfortable with the hash part of it, and it seems to be where the issue is. As I show in the code below, the "error" part gets echo'ed so it's something to do with the hash strings, but I don't really understand why changing to mysqli has broken the code. Both versions of the code are below, and the original code works. I deleted the variables (host name, etc.) but otherwise this is the code I am working with.
Mysql Code:
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
$db_link = mysql_connect($host_name, $user_name, $password) //attempt to connect to the database
or die("Could not connect to $host_name" . mysql_connect_error());
mysql_select_db($db_name) //attempt to select the database
or die("Could not select database $db_name");
return $db_link;
}
$db_link = db_connect(""); //connect to the database using db_connect function
// Strings must be escaped to prevent SQL injection attack.
$name = mysql_real_escape_string($_GET['name'], $db_link);
$score = mysql_real_escape_string($_GET['score'], $db_link);
$hash = $_GET['hash'];
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $hash) {
// Send variables for the MySQL database class.
$query = "insert into scores values (NULL, '$name', '$score');";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
}
Mysqli code (doesn't work):
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
$db_link = mysqli_connect($host_name, $user_name, $password) //attempt to connect to the database
or die("Could not connect to $host_name" . mysqli_connect_error());
mysqli_select_db($db_link, $db_name) //attempt to select the database
or die("Could not select database $db_name");
return $db_link;
}
$db_link = db_connect(""); //connect to the database using db_connect function
// Strings must be escaped to prevent SQL injection attack.
$name = mysqli_real_escape_string($_GET['name'], $db_link);
$score = mysqli_real_escape_string($_GET['score'], $db_link);
$hash = $_GET['hash'];
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $hash) {
// Send variables for the MySQL database class.
$query = "INSERT INTO `scores` VALUES (NULL, '$name', '$score');";
$result = mysqli_query($db_link, $query) or die('Query failed: ' . mysqli_error($db_link));
echo $result;
}
else {
echo "error"; //added for testing. This part gets echoed.
}
mysqli_close($db_link); //close the database connection
One notable "gotchu" is that the argument order is not the same between mysql_real_escape_string and mysqli_real_escape_string, so you need to swap those arguments in your conversion.
$name = mysqli_real_escape_string($db_link, $_GET['name']);
$score = mysqli_real_escape_string($db_link, $_GET['score']);
It's good that you're taking the time to convert, though do convert fully to the object-oriented interface if mysqli is what you want to use:
// Send variables for the MySQL database class.
function db_connect($db_name)
{
$host_name = "";
$user_name = "";
$password = "";
// Enable exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli($host_name, $user_name, $password);
$db->select_db($db_name);
return $db;
}
$db = db_connect(""); //connect to the database using db_connect function
$secretKey=""; # Change this value to match the value stored in the client javascript below
$real_hash = md5($name . $score . $secretKey);
if($real_hash == $_GET['hash']) {
// Don't include ; inside queries run through PHP, that's only
// necessary when using interactive MySQL shells.
// Specify the columns you're inserting into, don't leave them ambiguous
// ALWAYS use prepared statements with placeholder values
$stmt = $db->prepare("INSERT INTO `scores` (name, score) VALUES (?, ?)");
$stmt->bind_param("ss", $_GET['name'], $_GET['score']);
$result = $stmt->execute();
echo $result;
}
else {
echo "error"; //added for testing. This part gets echoed.
}
// Should use a connection pool here
$db->close();
The key here is to use prepared statements with placeholder values and to always specify which columns you're actually inserting into. You don't want a minor schema change to completely break your code.
The first step to solving a complex problem is to eliminate all of the mess from the solution so the mistakes become more obvious.
The last if statement is controlling whether the mysql query gets run or not. Since you say this script is echoing "error" form the else portion of that statement, it looks like the hashes don't match.
The $hash variable is getting passed in on the URL string in $_GET['hash']. I suggest echo'ing $_GET['hash'] and $real_hash (after its computed by the call to MD5) and verify that they're not identical strings.
My hunch is that the $secretKey value doesn't match the key that's being used to generate the hash that's passed in in $_GET['hash']. As the comment there hints at, the $secretKey value has to match the value that's used in the Javascript, or the hashes won't match.
Also, you may find that there's a difference in Javascript's md5 implementation compared to PHP's. They may be encoding the same input but are returning slightly different hashes.
Edit: It could also be a character encoding difference between Javascript and PHP, so the input strings are seen as different (thus generating different hashes). See: identical md5 for JS and PHP and Generate the same MD5 using javascript and PHP.
You're also using the values of $name and $score after they've been escaped though mysqli_real_string_escape, so I'd suggest making sure Javascript portion is handling that escaping as well (so the input strings match) and that the msqli escape function is still behaving identically to the previous version. I'd suggest echo'ing the values of $name and $score and make sure they match what the Javascript side is using too. If you're running the newer code on a different server, you may need to set the character set to match the old server. See the "default character set" warning at http://php.net/manual/en/mysqli.real-escape-string.php.
I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.
The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly
Main script:
<?php
include connect.db;
//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";
//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
$stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
$stmt->bind_param("ssss", $type, $username, $password, $email);
$stmt->execute();
$stmt->close();
echo "User Registered";
}
else {
echo "Username, password or email are already used";
}
?>
Connection Script:
<?php
//Identifies the databases details.
//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";
/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
die("Connection failed: " . mysqli_connect_error());
}
?>
edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.
Try to see the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
I'm creating a website which has a section dedicated to reviews and another one dedicated to users (log-in and sign up), both managed via databases.
In the reviews section, a user can give a review (via a form) which is uploaded in the database using this PHP code
<?php
if(isset($_POST['pulsanteRecensione']))
{
$host = "localhost";
$username = "root";
$password = "root";
$db_nome = "ristorante";
$tab_nome = "recensioni";
$link = mysqli_connect($host, $username) or die ('Impossibile connettersi: '.mysqli_error());
mysqli_select_db($link, $db_nome) or die ('Accesso non riuscito');
$nome = $_POST['nome'];
$recensione = $_POST['recensione'];
$sql = "INSERT INTO $tab_nome (`Nome`, `Recensione`) VALUES ('$nome', '$recensione')";
if(mysqli_query($link, $sql))
{
echo "<h4 align=\"center\">Inserimento avvenuto con successo</h4>";
}
else
{
echo "<h4 align=\"center\">Spiacenti, inserimento non riuscito</h4>";
}
}
?>
and it works. In the same way, I want to manage the users section, so I tried this PHP code for signing up that is more or less the same as the previous one
<?php
if(isset($_POST['effettuaRegistrazione']))
{
$nome = $_POST['nome'];
$cognome = $_POST['cognome'];
$mail = $_POST['email'];
$password = $_POST['password'];
$data = $_POST['dataNascita'];
$citta = $_POST['citta'];
$host = "localhost";
$username = "root";
$password = "root";
$db_nome = "ristorante";
$tab_nome = "utenti";
$link = mysqli_connect($host, $username) or die ('Impossibile connettersi: '.mysqli_error());
mysqli_select_db($link, $db_nome) or die ('Accesso non riuscito');
$sql = "INSERT INTO $tab_nome (`ID_Utente`, `Cognome`, `Nome`, `E-mail`, `Password`, `Data di nascita`, `Citta`) VALUES ('3','$cognome','$nome','$mail','$password','$data','$citta')";
if(mysqli_query($link, $sql))
{
echo "<h4 align=\"center\">Inserimento avvenuto con successo</h4>";
}
else
{
echo "<h4 align=\"center\">Spiacenti, inserimento non riuscito</h4>";
}
}
?>
but it doesn't work, it always shows Spiacenti, inserimento non riuscito. What am I doing wrong?
Here there is the structure of the utenti table
For one thing, you have an AI'd column (auto_increment).
You need to replace 3 in '3' with '' in VALUES.
mysqli_error($link) on the query would have signaled the error.
You also shouldn't be storing plain text passwords or as integers (see my note about that further down).
Use password_hash() and a prepared statement as you are open to an SQL injection here.
Use error reporting in case your POST arrays fail.
http://php.net/manual/en/function.error-reporting.php
However, your $link = mysqli_connect($host, $username) and mysqli_select_db($link, $db_nome) may be failing here.
Use all four arguments for it and if there is no password for the db required, use '' only.
I.e.:
$link = mysqli_connect($host, $username, '', $db_nome);
If your present method works, then disregard that ^
Another thing; the password column as an int(15), that doesn't seem to make much sense and it is not a secure method.
Password columns are usually varchar and using a minimum 60 length to save a safe hash, such as password_hash(); the manual on password_hash() says that 255 is a good bet.
Also, mysqli_error() requires a db connection for it mysqli_error($link).
You also need to make sure that the columns' lengths are long enough to hold the data. That in itself could fail silently or truncated.
Note:
Your entire code's execution is relying on this conditional statement:
if(isset($_POST['effettuaRegistrazione'])) {...}
If that fails, so will your entire query.
Plus, as stated in comments (by Jeff):
You're using the same variable for $password for both the POST array and the possible password for your db login; you need to change one of those.
I am using the following code to insert Event Logs and User Info from my Mobile App to a mysql database.
I am finding the " Character gives me issues later on when in use with JSON arrays that I pull from the db. What I would like to do is remove the " character in the php code completely before posting to the db.
Removing the " character by Javascript from the Mobile App is not really an option.
<?php
$servername = "localhost";
$username = "Fred";
$password = "Barney";
$dbname = "BamBam";
// Create connection
$conn = new mysqli ($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// escape variables for security
$event_log = mysqli_real_escape_string($conn, $_POST['event_log']);
$logged_by = mysqli_real_escape_string($conn, $_POST['logged_by']);
$sql = "INSERT INTO time_event (event_log, logged_by)
VALUES ('$event_log', '$logged_by')";
if ($conn->query($sql) === TRUE) {
echo "Data entered successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Use mysqli_prepare and mysqli_stmt_bind_param to execute a parameterised query. I strongly advise this approach.
If you really want to just escape special characters for manual interpolation
into a query string, use mysqli_real_escape_string.
Hand-rolling a solution presents a real risk that you will
miss something important, leaving your program vulnerable
to SQL injection attacks.
I did not try, but this should do
$sql = sprintf("INSERT INTO time_event (event_log, logged_by)
VALUES ('%s' ,'%s'",$event_log,$logged_by);
I've spent most of the day trying to get data from a form into a MySQL Database, everything I have tried so far has not worked, can anyone figure out what is wrong? The database is connecting fine, it just cannot add any data into the mysql database (current errors are at the bottom)
EDIT: Updated Code Below (Still not working!)
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "report"; // Database name
$tbl_name = "tbl_nonconformance"; // Table name
// Connect to server and select database.
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
echo "Database Connected ";
$name = $_POST['name'];
$email = $_POST['email'];
$supplier = $_POST['supplier'];
$PONum = $_POST['PONum'];
$Part = $_POST['Part'];
$Serial = $_POST['Serial'];
$tsf = $_POST['tsf'];
$Quantity = $_POST['Quantity'];
$probclass = $_POST['probclass'];
$desc = $_POST['desc'];
$sql="INSERT INTO tbl_nonconformance (sno, Date, Name, Email, Supplier, PONum, Part, Serial, TSF, Quantity, probclass, desc)
VALUES
('$sno', '$date', '$name', '$email', '$supplier', '$PONum', '$Part', '$Serial', '$TSF', '$Quantity', '$probclass', '$desc')";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
header('Location: ../thankyou.php');
}
else {
echo "ERROR";
}
// close mysql
mysql_close();
?>
First you should change
mysql_connect("$host", "$username", "$password") or die("cannot connect");
to:
$con = mysql_connect($host, $username, $password) or die("cannot connect");
You are calling $con but you never defined it. You want to save your MySQL connection (con) as $con for what you are trying to do here.
You should also really consider upgrading to MySQLi as MySQL is deprecated from PHP and will likely be removed from future versions. Here's a resource to get you started. http://www.php.net/manual/en/book.mysqli.php
Edit July 9 2014: You updated your code, and I do not recall what your original code was. Still, if it's not "working", it's best to describe how it's not working. After you call $result, do this:
if( !$result || !mysql_affected_rows() )
die( mysql_error() );
header('Location: ../thankyou.php'); //this will only occur if there are no SQL errors and the result actually inserted something
mysql_close();
echo "We couldn't forward you automatically. Click here to proceed {insert HTML/JS here}";
This will return the MySQL error message which will help you in your debugging.
You got your argument parsing wrong.
$name = mysql_real_escape_string($con, $_POST['name']);
$con is not defined first of all.
Secondly you are trying to escape $_POST['name'].
mysql_real_escape_string expects 2 arguments, 1st one is mandatory and second one is optional. First argument is the string you want to escape, the second specifies a mysql connection (optional as you may have one open already).
So your statement needs to look like
$name = mysql_real_escape_string($_POST['name']);
Perhaps $con is your mysql connection? Which if it is the case you may want to
$con = mysql_connect ........ and so on
you're using un-secure depreciating methods too. You should research PDO object. It separates variables from your query so they aren't sent at the same time. It also cleans code considerably. I see a few problem areas in his code... You pass in $sno, $date, but they don't exist in your code. $tsf has a different case in instantiation then what you're using in your query. You're using single quotes which can't interpolate data (place values where variable names are). Double quotes do that...
hmmm...
check this out.
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_port = "3306" // Mysql port
$db_name = "report"; // Database name
$dsn = "mysql:dbhost=$host;dbport=$db_port;dbname=$db_name";
//add sno variable declaration here.
$name = $_POST['name'];
$email = $_POST['email'];
$supplier = $_POST['supplier'];
$PONum = $_POST['PONum'];
$Part = $_POST['Part'];
$Serial = $_POST['Serial'];
$TSF = $_POST['tsf'];
$Quantity = $_POST['Quantity'];
$probclass = $_POST['probclass'];
$desc = $_POST['desc'];
$date = date('d-m-Y');
// Connect to server and select database.
$dbConnect = new PDO($dsn, $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sqlStatement = $dbConnect->prepare("INSERT INTO tbl_nonconformance (sno, Date, Name, Email, Supplier, PONum, Part, Serial, TSF, Quantity, probclass, desc)VALUES('?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')");
try{
$sqlStatement->execute(array($sno, $date, $name, $email, $supplier, $PONum, $Part, $Serial, $TSF, $Quantity, $probclass, $desc));
header('Location: ../thankyou.php');
}catch(\PDOException $e){
echo 'Error: Could not connect to db.';
}
?>
PDO object is really easy. create $dbConnect = new PDO(). You see the arguments there. dsn, username, password. The last argument is just an associative array setting PDO's error mode with constants. This allows us to use the try catch block to do error handling. IF PDO can't connect we get the catch block to fire...otherwise the try block which is where our data is sent to the db... You see we have a variable called $sqlStatement.. this is made through $dbConnect->prepare(). This function takes the statement... notice variables are excluded for question marks. Inside the try block we call execute from the statement...this takes and array of values that will replace the question marks in order.
remember to create sno variable. I added date for you. also be sure all cases and spellings are right. One letter in your query string, whether spelled wrong, or even just cased wrong will cause a failure.
let me know if there's any errors or questions. jeremybenson11#gmail.com