I am learning to put data in my database using php mysqli prepared statements. I have the data going into the data base by using this code.
$FirstName=ucwords($_POST['fname']);
$LastName=ucwords($_POST['lname'], "-'");
$Customer=$LastName." ".$FirstName;
$conn = new mysqli($host,$user,$password,$db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO customers (FirstName, LastName, Customer) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $FirstName, $LastName, $Customer);
$stmt->execute();
$conn->close();
This is working very well. Especially with hyphenated names or names with an apostrophy such as Pete O'Brian.
Now then while trying to retrieve the information back out of the database I am using the following code.
$conn = new mysqli($host,$user,$password,$db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn -> prepare("SELECT Customer, Instrument1 FROM tblinvoice WHERE InvID = ?");
$stmt->bind_param("i", $tempid);
$stmt->execute();
$stmt -> bind_result($cust, $inst);
$stmt -> fetch();
$cust = mysqli_real_escape_string($conn, $cust);
$stmt -> close();
$conn -> close();
BUT the above output O\ for a last name of O'Brian. If I remove the mysqli_real_escape_string($conn, $cust) and just use the bound value of $cust I simply get O instead of O'Brian.
Can anyone tell me what I am not doing or what I am doing wrong here?
always use htmlspecialchars() in content from db that are going to show in html.
echo htmlspecialchars($yourresult['yourfield'], ENT_QUOTES);
We should always use htmlspecialchars when filling HTML form input fields values.
Related
Please i have a little problem here. the below code i wrote was meant to insert into two tables simultaneously but it those not work. but if i remove the second INSERT the first INSERT will work dont know whats wrong. ITs meant insert in the first table and also collect the last Insert Id of the First table to the Second table. What did i do wrong
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
$query .= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>
its almost 2018, so please stop using depreciated and removed mysql_* functions use PDO/mysqli with prepared statements.
I have re-written your code with prepared statements, please follow these links :
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
Prepared statements
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "fruitmarket";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = "INSERT INTO data (english_name,tel_number,email_address,gender,age,region) VALUES(?,?,?,?,?,?)";
$sql = $conn->prepare($stmt);
$sql->bind_param("ssssis", $english_name, $tel_number, $email_address, $gender, $age, $region);
if ($sql->execute()) {
$id = $sql->insert_id;
$insert = $conn->prepare("INSERT INTO data_category (id, english_name) VALUES(?,?)");
$insert->bind_param("is", $id, $english_name);
if ($insert->execute()) {
echo "data inserted successfully";
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
Prepared statements basically work like this:
Prepare: An SQL statement template is created and sent to the
database. Certain values are left unspecified, called parameters
(labeled "?"). Example: INSERT INTO myTabvle VALUES(?, ?, ?)
The database parses, compiles, and performs query optimization on
the SQL statement template, and stores the result without executing
it
Execute: At a later time, the application binds the values to the
parameters, and the database executes the statement. The application
may execute the statement as many times as it wants with different
values Compared to executing SQL statements directly, prepared
statements have three main advantages:
Prepared statements reduces parsing time as the preparation on the
query is done only once (although the statement is executed multiple
times)
Bound parameters minimize bandwidth to the server as you need send
only the parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because
parameter values, which are transmitted later using a different
protocol, need not be correctly escaped. If the original statement
template is not derived from external input, SQL injection cannot
occur.
I tested the above code and noticed you just need just to add and change some code see my below example
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
$query= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>
test it to check if it will work
I am very new to PHP and MySQL. I have the following code that works but now I need to incorporate prepared statements into. I have tried many things but with no luck.
The following is the original PHP code:
$sql = "SELECT name, address, city, phone, id FROM Lab7 WHERE name = '$name' ";
mysql_select_db('muftih_Registration');
$retval = mysql_query( $sql, $conn );
This is my attempt that did not work:
$sql = "SELECT name, address, city, phone, id FROM Lab7 WHERE name = ?";
$sql->bindParam('s', $name);
mysql_select_db('muftih_Registration');
$retval = mysql_query( $sql, $conn );
I keep getting:
Fatal error: Call to a member function bindParam() on a non-object
The mysql_ family does not support prepared statements, you'll need to migrate to mysqli_ which is a different driver library. Furthermore, you cannot mix mysql_ and mysqli_ libraries together.
Lastly, mysql_ has been deprecated for several years now, and has been removed in php 7.
Synopsis: do not use mysql_.
You need to use mysqli on order to use prepared.
Let me show an example.
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("SELECT name, address, city, phone, id FROM Lab7 WHERE name = ?")) {
$stmt->bind_param("s", $name);
$stmt->execute();
$stmt->bind_result($name, $address, $city, $phone, $id);
$stmt->fetch();
echo "$name, $address, $city, $phone, $id"; // Print the retrieved row
$stmt->close();
}
Hope this helps.
Peace! xD
I am having getting my query to display results, I have ran the exact same query locally in mySQL and I get the desired result but when it is executed through the following code nothing happens.
$JobID = '3214.GF.010.J45.TEA';
$ProjectID = '3214';
$conn = new mysqli ($server,$username,$password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br>";
$stmt = $conn->prepare('Select jmpPartShortDescription, ujmpLevel, ujmpRoom, jmpClosed from Inf_Jobs');
//$stmt->bind_param('ss',$JobID,$ProjectID);
$stmt -> bind_result($Description,$Level,$Room,$Closed);
$stmt -> fetch();
$stmt -> close();
$conn -> close();
echo $Description .$Level .$Room .$Closed;
I cannot understand why I get no results I am getting the Connected Successfully message but no actual values are returned.
You need to execute() a prepared statement to make it do anything.
$stmt = $conn->prepare('Select jmpPartShortDescription, ujmpLevel, ujmpRoom, jmpClosed from Inf_Jobs');
//$stmt->bind_param('ss',$JobID,$ProjectID);
$stmt->execute(); // <- this is what does the work
$stmt -> bind_result($Description,$Level,$Room,$Closed);
$stmt -> fetch();
I am just learning to use prepared statements and stuck here. there is no problem with normal method. there is nothing error shown but the data is not stored in database although it displays "data entered".
$db = new mysqli("localhost", "root","","learndb");
if ($db->connect_error) {
die("Connection failed this is the error: " . $db->connect_error);
}
$stmt = $db->prepare("INSERT INTO studentrecords (Name, email, Phone, school,dob,father,feereceived,due,image) VALUES (?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("ssisssiib",$first,$email,$phone,$school,$dob,$father,$feereceived,$due,$image);
$stmt->execute();
if($stmt)
{
echo"data entered";
}
Update
Data is stored but not the type required. should i specify all types in user input? Also the pattern in html form not working.
I'd suggest that you wrap the entire bind_param & execute with an if condition as the statement will fail to be prepared if there is even a minor issue. In this case I would guess it could be that the types for each variable/field is wrong at some point - probably the image / b part.
You can echo the type of each using gettype which might help track it down:
echo gettype($first), gettype($email), gettype($phone),
gettype($school), gettype($dob), gettype($father),
gettype($feereceived), gettype($due), gettype($image);
$db = new mysqli("localhost", "root","","learndb");
if ($db->connect_error) {
die("Connection failed this is the error: " . $db->connect_error);
}
$stmt = $db->prepare("INSERT INTO studentrecords (`Name`, `email`, `Phone`, `school`,`dob`,`father`,`feereceived`,`due`,`image`) VALUES (?,?,?,?,?,?,?,?,?)");
if($stmt) {
$stmt->bind_param("ssisssiib",$first,$email,$phone,$school,$dob,$father,$feereceived,$due,$image);
$stmt->execute();
} else {
echo 'Failed to prepare the sql statement';
}
I apologise if the title is poor.
I have been researching Prepared Statements and found the following code here:
/* Create a new mysqli object with database connection parameters */
$mysqli = new mysqli('localhost', 'username', 'password', 'db');
if(mysqli_connect_errno()) {
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
/* Create a prepared statement */
if($stmt = $mysqli -> prepare("SELECT priv FROM testUsers WHERE username=?
AND password=?")) {
/* Bind parameters
s - string, b - blob, i - int, etc */
$stmt -> bind_param("ss", $user, $pass);
/* Execute it */
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($result);
/* Fetch the value */
$stmt -> fetch();
echo $user . "'s level of priviledges is " . $result;
/* Close statement */
$stmt -> close();
}
/* Close connection */
$mysqli -> close();
The part that I don't understand, is how in the SQL Query "SELECT priv FROM testUsers WHERE username=?
AND password=?"), the system knows what the username and password is. I know that the ? marks are placeholders, and below is also confusing me a bit:
$stmt -> bind_param("ss", $user, $pass);
Because I do not see how the $user and $pass have been defined at any point, and thus how the SQL query will substitute the $user and $pass for an actual string. If that makes sense. Where have these values come from? Where are they in this example?
That's because they aren't. This is probably just an example how to use the script. You will have to define the $user and $pass variables by yourself, for example from an $_POST variable of some sort.
The bind_param function handles the arguments. You have to add the same amount of arguments to the query as you put question marks in it. Than the parser in the core of MySQLi can add the arguments safely to the query.
They are being matched by order. Same logic in string building ("{0} is greater than {1}", "5", "3") becomes 5 is greater than 3. So with parameters
$stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent);
they are all ordered and matches with columns.
If the original script writer had register_globals ON, e.g. in a previous version of PHP, then the user and pass were passed in from the form in the same way as $_POST['user'] and $_POST['pass']. I offer that you can replace them now and move on.