简体   繁体   中英

How to get all data from MySQL with apostrophe in it using PHP

I am trying to pull data from MySQL record that has an apostrophy. It comes back with a backslash and rest of string missing. Trust me, I have scoured the internet and nothing so far is working. I must be too tired out on it and it is right in front of me. See code below ...

$sql = "SELECT * FROM ".$tbl."  WHERE FIELD_NO = ".$order_no." ORDER BY LINE_NO ASC";
    $rs_result = $conn->query($sql); 

while($row = $rs_result->fetch_assoc()) {

$addl_info = mysqli_real_escape_string($conn, $row['ADDL_INFO']); //tried this

echo "<td class='col32'><input name='addl_info[]' class='addl_info' type='text' value='".$addl_info."'></td>";

The mysql stored data is "Band of 20's" and it outputs as "Band of 20\\" with the 's' missing. I tried everything I can imagine and still I cannot get my full data string returned using PHP. I used mysqli_real_escape_string() to get the data in with the apostrophe but now I cannot get the data back out with the apostrophe and the text that follows it.

I plan to use this particular project to move over to PDO, but I need a fix for now until I can do that. It will take me some time to learn and accomplish PDO.

You're enclosing your value in single quotes, this won't work:

value='Band of 20's'

See the problem? How would the browser know which is a starting quote and which is an ending one?

You need to convert the quote into it's HTML entity &#039; :

echo "stuff value='".htmlentities($row['ADDL_INFO'], ENT_QUOTES)."' stuff";

Or use double quotes (however you should still convert HTML entities):

echo "stuff value=\"{$row['ADDL_INFO']}\" stuff";
//or
echo 'stuff value="'.$row['ADDL_INFO'].'" stuff';

Running mysqli_real_escape_string() on a string like you do here escapes certain characters:

$addl_info = mysqli_real_escape_string($conn, $row['ADDL_INFO']);

You just need to retrieve the value returned:

$addl_info = $row['ADDL_INFO'];

Also, for security reasons (risk of SQL injection) make sure to run your query through a prepared statement. You can find information about doing that here: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Access you SQL from a broswer, PHP my Admin or similar... When you see your table and all other tabs go to SQL. It is like a test environment where you can try your code. There are some presets like "Select * from table" etc. There you can see how the apostrophe is written in your SQL. I think it will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM