0

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?

1
  • Use mysql_real_escape_string on INSERT not on SELECTm if you so, you don't need to escape anything on the output Commented Oct 11, 2015 at 19:17

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

GREAT thank you now using htmlspecialchars. I had already escaped the string on the insert so i removed the escape on the retrival and now I get the expected results!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.