I'm using ajax to gather the ckeditor data to be submitted. The problem is only the content before the first apostrophe is being submitted to the database. What could I be doing wrong?
Edit:
$date = strtotime($formData['date']);
$article=mysql_real_escape_string($formData['article'],$DBconnect);
$DBconnect=mysql_connect($dbVals['host'],$dbVals['user'],$dbVals['pass']);
mysql_select_db($dbVals['db'], $DBconnect);
$SQLstring="INSERT INTO PressRelease (ip, tym, title, date, article) VALUES('${_SERVER['REMOTE_ADDR']}', ".time().",'${formData['title']}', '$date', '$article')";
I'm fairly new at this so if there is anything else you need to see in order to help let me know.
It sounds like you aren't escaping the text data before you insert it into the database. Use this function on the data before you pass it into your SQL query:
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Edit: sorry, that's assuming you are using MySQL.
A different, more complicated, and arguably superior method to the one suggested by Mark, is using Parameterized Statements.
To borrow an example from Wikipedia:
<?php
$db = new mysqli("localhost", "user", "pass", "database");
$stmt = $db -> prepare("SELECT priv FROM testUsers WHERE username=? AND password=?");
$stmt -> bind_param("ss", $user, $pass);
$stmt -> execute();
?>
It leaves the escaping up to the MySQL driver, severely reducing the chance of SQL Injection and things like accidental double-escaping.
Note that this is not possible using the old MySQL functions. You need the Improved MySQLI functions/object, or something like PDO.
If I understand correctly the following is the case:
You've got a textarea that's "taken over" by CKeditor
You're reading the content of that textarea with Javascript
You're sending the gathered content to the server with AJAX
If you alert() the content that Javascript gets from the textarea, you can see whether step 2 succeeds. If not, please post your Javascript.
If step 2 is correct, then maybe there's a problem server side, dump your db query to look at that.
Update:
Make sure you when you're developing that you turn on all errors and notices. And if you're doing stuff which you can't "see" easily, like AJAX, make sure to keep an eye on your server's error log.
In your code example line 2 you use $DBconnect, and then in line 4 you define what that is. As you can see in the PHP.net entry for mysql_real_escape_string if the function cannot find a connection to the database the function generates an error and returns FALSE. The FALSE is put into your database and that's what goes into your database.
My advice to you is: try harder at debugging. Test all your assumptions, test the value of variables at every step, check if they have the value you expect them to have. Use var_dump(), print_r(), echo and die(). Or if you want something more advanced use a debugger (I don't).
Related
Here is my code below:
$studentTalking = mysql_real_escape_string($_POST['studentTalking']);
//Finally, we can actually the field with the student's information
$sql = <<<SQL
UPDATE `database` SET
`studentName`='$studentName',
`studentEmail`='{$data['studentEmail']}',
`studentPhone`='{$data['studentPhone']}',
`studentID`='{$data['studentID']}',
`studentTalking`= '{$studentTalking}',
`resume` = '{$data['resume']}'
WHERE `id`={$data['date_time']} AND (`studentName` IS NULL OR `studentName`='')
SQL;
I am trying to use the mysql_real_escape_string to allow apostrophes entered into our form by the user to go to the database without breaking the database, however the data will either go through as null or the apostrophe will break the database. I have changed everything I could think of, and can't figure out why this isn't working. Yes I understand the that injections could break our database, and we will work on updating the code soon to mysqli but we need this working now. I suspect my syntax isn't correct and the first line may need to be moved somewhere, but I am not the strongest in PHP and I am working with code that was written by previous interns. Thank you in advance.
Switch to mysqli_* functions is the right answer.
The answer if intend to stayg with the deprecated and dangerous mysql_* functions:
Here you set a new variable equal to your escaped $_POST[]:
$studentTalking = mysql_real_escape_string($_POST['studentTalking']);
But in your SQL you still refer to the $_POST array... Switch your SQL over to use your new variable you created
$sql = <<<SQL
UPDATE `tgtw_rsvp` SET
`studentName`='$studentName',
`studentEmail`='{$data['studentEmail']}',
`studentPhone`='{$data['studentPhone']}',
`studentID`='{$data['studentID']}',
`studentTalking`= '$studentTalking',
`resume` = '{$data['resume']}'
WHERE `id`={$data['date_time']} AND (`studentName` IS NULL OR `studentName`='')
SQL;
Because you are not using the stripped variable but still the raw POST data.
So i built an application in mysql, and was having challenges updating records in the db. Everybody was more interested in telling me that i should just use PDO.
So rather than fight, I decided to start to learn PDO connection and query strings and the practices around using prep stmts.
Anyway in my practice and tutorials, I can pull and parse the information from my database with no challenges. but when it comes to updating or inserting a new record nothing is ever inserted and I can't find the reason why not.
originally I had a form post to the variables, but that didn't work
so i hardcoded the variables, but it still isn't working
i could use some help.... can anybody see what is wrong with this insert php script?
<?php
$user="111";
$pass="111";
$database="111";
$host="111";
$odb = new PDO("mysql:host=$host;dbname=$database", $user, $pass);
$event='Special Speaker';
$descript='We have special speakers comming on tuesday night';
$sp1='Speaker Mr.A';
$sp2='Speaker Mr.B';
$date='5-5-15';
$created = '5-5-15';
$id=7;
$stmt=$odb->Prepare("INSERT INTO events(ID,Event,Descript,Sp1,Sp2,Created,Date)
VALUES (:ID,:Event,:Descript,:Sp1,:Sp2,:Created,:Date");
$stmt->bindParam(':ID',$id);
$stmt->bindParam(':Event',$event);
$stmt->bindParam(':Descript',$descript);
$stmt->bindParam(':Sp1',$sp1);
$stmt->bindParam(':Sp2',$sp2);
$stmt->bindParam(':Created',$created);
$stmt->bindParam(':Date',$date);
$stmt->execute();
?>
You may have to specify that your ID is an int like so: $stmt->bindParam(':calories', $calories, PDO::PARAM_INT);
Your database may be preventing you from inserting IDs in that table if it's the Identity/Primary column and/or is auto-incrementing.
It'd be a good idea to enable PDO warnings or exceptions so that it can tell you what's wrong or what is failing. See here for more: http://php.net/manual/en/pdo.error-handling.php
[UPDATED] with new code "sql_real_escape_string()"
[UPDATED] if anyone wants to look at the site its at Test site
[UPDATED] with the while code showing any results via echo
Hello All,
I have looked at many posts on this matter, but simply cannot understand why the following code doesn't work:
$username = $_POST['username'];
// get the record of the user, by looking up username in the database.
$query = sprintf("SELECT UserName, Password FROM userlogin WHERE UserName='%s'", mysql_real_escape_string($username));
$result = mysqli_query($dbc, $query) or
die ("Error Querying Database for: " . $query .
"<br />Error Details: " . mysql_error() . "<br/>" . $result);
while ($row = mysqli_fetch_assoc($result))
{
Echo($row['UserName']);
}
The Code seems to be correct... the database is working perfectly (for input purposes) and the connection is a shared connection applied with require_once('databaseconnection.php'); that is working for the registration side of things.
like normal I'm sure this is something simple that I have overlooked but cannot for the life of me see it!
I do not get any error messages from the myssql_error() its simply blank.
any help would be much appreciated.
Regards
Check the username you try to query as it might be empty. Do you really use a post-request to run that script? How do you verify that it does not work? What do you do with $data after the query?
If just nothing seems to happen it is likely your query did not match any record. Check for whitespace and case of the username you are looking for.
Mind those warnings:
Use a prepared statement or at least sql-escape any user-input before using it in sql.
Don't use die in serious code only for debugging.
The $data will contain a result object. You need to iterate over it using something like mysqli_fetch_assoc($data).
Also, you can interpolate variables directly into double quoted strings - i.e. UserName='".$username."'" could be written more cleanly as UserName='$username' rather than breaking out of the string.
Also, please sanitize your input - all input is evil - using mysqli_real_escape_string() function. You've got a SQL injection exploit waiting to happen here.
Bear in mind that it's a very good idea to validate all data to be inserted into a database.
Very often you have problems with query itself, not implementation. Try it in phpMyAdmin first and see if there are any problems.
Check server logs.
BY THE WAY: Never put variables from POST to query! That's definitely a SQL injection'
You might have some issue with the query.
Have you Tried to echo the $query and run that directly with mysql client or workbench?
This piece of code seems ok. That is, if $dbc contains an actual database connection. But the choice of naming that variable $data while the function actually returns a result object or a boolean, indicates that you may process the data wrong.
If that is not the problem, we'll definately have to see more code.
Try printing $data variable instead of printing only query. Check, whether you are able to get any error messages. If you could see any data then you should use mysql fetch function to iterate things. Try it.
PLEASE READ THE QUESTION CAREFULLY. It is not usual silly "my code doesn't work!!!" question.
When I run this code with intended error
try {
$sth = $dbh->prepare("SELECT id FROM users WHERE name INN(?,?) ");
$sth->execute(array("I'm","d'Artagnan"));
} catch (PDOException $e) {
echo $e->getMessage();
}
I get this error message
You have an error in your SQL syntax ... near 'INN('I\'m','d\'Artagnan')' at line 1
But I thought for years that query and data being sent to the server separately and never interfere. Thus I have some questions (though I doubt anyone got an answer...)
Where does it get such a familiar string representation - quoted and escaped? Is it being made especially to report an error or is it a part of actual query?
How does it work in real? Does it substitute a placeholder with data or not?
Is there a way to get whole query, not only little bit of it, for debugging purposes?
Update
mysqli does it as expected: it throws an error says near 'INN(?,?)'
try adding
$dbh->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
;)
I'm not sure about all the details, but I will try to answer.
The quotation happens on the database side. The database escapes and sanitizes all values (see bullet 2) it receives so that it gets interpreted correctly.
The moment the error is thrown, the database (in this case MySQL) prints out the query it tried to run. This wouldn't be so helpful if it just showed the prepared part.
No, it doesn't. At preparation time the query gets compiled on the server side. When a query is executed with values, only the values are transmitted. This is pretty much the same as calling PREPARE and EXECUTE on the database directly.
This depends on the database you're using. MySQL for example can log all queries to a log file (check my.cnf settings for that). But you can also use debugDumpParams() on PHP side.
I hope this was a bit helpful.
This is a terrible question because I don't have a simple way to reproduce it. However, I'm using the Zend Framework to connect to my MySQL database on OS X. Sometimes a call to the prepare function on a mysqli object returns null. The stated return values for the prepare function are false or a statement object.
I can't figure out where else to look for info on why the prepare statement is failing. Is there any way to get visibility into the prepare process to see why it is failing? All of my problems are coming up while a transaction is open.
Sorry for the lack of specifics, but I really can't nail down why this is happening.
Just to correct ToughPal, you should be using:
mysqli_query($db, "INSERT INTO table (variable1, variable2) VALUES (hello, mynameis);
Remember that you need to have the db connection defined and stated in the query first, before your actual SQL.
Remember to enclose the table name, column names and value data in backtick escapes.
Example prepared statement
$result = $db->query( 'INSERT INTO server (key, value) VALUES (:key, :value)',
array('key' => $foo, 'value' => $bar)
Can you let us know your DB query?
Try and execute your DB query with test data and see if the query works fine to start with. If the query is ok then we can look why the code fails.
Well I managed to find the issue over the weekend but was really only able to fix the symptoms and not the cause.
I didn't include any SQL in the original issue because the problem was happening randomly, the same code would sometimes work and sometimes not. The issue looks like it was a memory pointer problem. Whenever I had a problem Zend Debugger told me that I had a mysqli object. I believe this because otherwise I would've gotten an error when trying to run the prepare function on it. I have a singleton object that acts as a container for my mysqli connection but whenever the prepare function failed, === showed that the mysqli being used was not the same as the mysqli connection in my singleton object.
In the end, Zend Framework's only issue is that it doesn't fail if the the prepare function returns null. If you are seeing this problem use === to verify that the connection is actually the same as the one that you've previously initiated.
if you're doing something like this
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$query = "...";
$mysqli->prepare($query);
then you can inspect mysqli::$error next to see useful errors about why prepare() failed
print_r($mysqli->error);