Jump to content

Inserting Strings in a Sql field


ameliabob

Recommended Posts

I am trying to insert a string in a single field but cannot figure out what the syntax should be

 

 

$s ="abc";
$s .=",def";
 
$qry = "INSERT INTO ".table." (baseID,tableName,fieldNames) VALUES ('8','headerfields' , '' ".$s." ' )";

 

This gives me the:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near...

 

How do I encapsulate the $s string to not have this count as additional fields?

 

Thanx

Link to comment
Share on other sites

This leaves you open to SQL injection (people can hack your database), be sure your strings are sanitized.

 

For database connection you should look into prepared statements. This will completely remove your syntax problem and additionally ensure nobody can hack you.

 

The thing prepared statements don't do, though, is give placeholders for table and field names. For these you'll have to manually sanitize and add the strings. To sanitize table names I recommend removing any backticks from the input string before adding it to the query and wrapping the table name in backticks

// This value could come from anywhere, but for the sake of security, it might be better to just hardcode it right into the SQL string
$table = 'my_table';

// Sanitize table name
$table = str_replace('`', '', $table);

// Create the SQL
$sql = "INSERT INTO `$table` (baseID, tableName, fieldNames) VALUES (?, ?, ?, ?)"

// Instantiate a PDO object
$pdo = new PDO( ... );

// Prepare the query
$query = $pdo->prepare($sql);

// Execute the query with the data
$data = array(
  8, // baseID
  'headerfields', // tableName
  'abc,def', // fieldNames
);
$success = $query->execute($data);

Could you explain why you want to store data about a table in another table? This whole thing is probably not necessary.

Link to comment
Share on other sites

I am setting up a testing database where the preconditions of the data are stored and some step is performed and then the results are compared to what they should have become.

 

In the previous example it might have been easier to have:

$fieldValues = "'true,43,right";

 

and after the same area would have $answer ="false,43,left"

 

so I would preload a file execute a program and then see if $fieldValues had changed to $answer

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...