Jump to content

[SOLVED] String crashes my script


EchoFool

Recommended Posts

Quick question, i have a variable holding a string like this:

 

"Username's query"

 

Now when i put this into a query the ' symbol is causing it to crash, what can i do to prevent that upon the moment a query occurs?

 

I have this at the moment:

$row = mysql_fetch_assoc($Check);

$Name = stripslashes(mysql_real_escape_string($row['Name']));

 

But that doesn't fix the issue :(

Any suggestions?

Link to comment
https://forums.phpfreaks.com/topic/114084-solved-string-crashes-my-script/
Share on other sites

what is the code before this where you generate the query? cus you have to escape it BEFORE the mysql_query() command...

 

<?php
  $user = mysql_real_escape_string($_POST['user']);
  $sql = "SELECT * FROM users WHERE user = '$user'";
  $Check = mysql_query($sql) or die(mysql_error());
  $row = mysql_fetch_assoc($Check);
  $Name = $row['Name'];
?>

Yes its before the query insert occurs.

 

The string comes from the database so its in the database as Username's Query. Though this didn't go through a stripslashes upon insert, however it does go through the mysql_real_escape_string.

 

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 's Query','4','2008-07-10 15:55:29')' at line 2

 

Thats the error you can see it starts from the 's Query.

 

My code:

      $Name comes from the database and it equals "Username's Query".

 

       

<?php
       $TableName = 'logs';
$Log = 'Ths is '.$Name;

$INSERT = mysql_query("INSERT INTO $TableName (Log,UserID,LogTime)
		VALUES ('$Log','{$_SESSION['Current_User']}','$Date')")
			Or die(mysql_error());
?>

Using mysql_real_escape_string only preps data for a mysql_query. It doesn't alter the value that is in the DB.

 

If you echo the query you are sending to MySQL, you will see it is:

INSERT INTO logs (Log,UserID,LogTime) VALUES ('Ths is Username's Query','4','2008-07-10 15:55:29')

the ' in the username is throwing off mysql because it thinks it's the end of the string. you need to escape that string with mysql_real_escape_string:

 

<?php
       $TableName = 'logs';
$Log = mysql_real_escape_string('Ths is '.$Name);

$INSERT = mysql_query("INSERT INTO $TableName (Log,UserID,LogTime)
		VALUES ('$Log','{$_SESSION['Current_User']}','$Date')")
			Or die(mysql_error());
?>

 

before you send anything that might have apostrophes to mysql_query it should go through mysql_real_escape_string(). you don't need to send the userid and logtime through cus we know it's already safe (but it doesn't hurt to send it through)

 

make sense?

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.