Jump to content

need help with htmlspecialchars() syntax


webguync

Recommended Posts

Hi,

 

I am trying to add htmlspecialchars() to my form fields to allow for special characters in the fields. What I have below produces a SQL syntax error. Can anyone help w/ the syntax?

 

 

<?php
$con = mysql_connect("localhost","uname","pw");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("DBName", $con);

$sql="INSERT INTO table (employee_id, employee_name, assessor_id, assessor_name)
VALUES
htmlspecialchars('$_POST[employee_id]','$_POST[employee_name]','$_POST[assessor_id]','$_POST[assessor_name]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)
?> 

Link to comment
https://forums.phpfreaks.com/topic/173157-need-help-with-htmlspecialchars-syntax/
Share on other sites

Several problems there.

 

1. You are trying to run a function within the query string. If you need to run a function on a value it needs to be outside the delimiting strings.

 

2. You can run htmlspecialchars() on the values before inserting into the database, but I would suggest against it. If youneed a method for those values to be edited you will have to find a way to revert the code to it's original state - which may not always be possible. I suggest saving the data "as entered" into the database, then use the approritate method when displaying the value. So if you are displaying the value on the page in the HTML content then use htmlspecialchars(). But, if you need to poulate the text back into the textarea to be edited, then you don't need to do anything.

 

However, you should always use mysql_real_escape_string() when saving user submitted values to the db. Your query could look something like this:

 

$employee_id = mysql_real_escape_string($_POST['employee_id']);
$employee_name = mysql_real_escape_string($_POST['employee_name']);
$assessor_id = mysql_real_escape_string($_POST['assessor_id']);
$assessor_name = mysql_real_escape_string($_POST['assessor_name']);

$sql="INSERT INTO table (employee_id, employee_name, assessor_id, assessor_name)
       VALUES ('$employee_id','$employee_name','$assessor_id','$assessor_name')";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.