Am running a sql query with php to retrieve some data from mysql database.
Everything works well except that, if the data contains symbols like < and >, then whatever data present between these symbols doesnt show in the output.
for example, if the data is something like "<hello there> how are you?" then only "how are you?" is shown.
But when i run the query directly, it shows me everything without missing anything.
I have done this before, but I cannot remember on the top of my head as what exactly I did. And google is not helping me today, slow day for me.... :(
You should escape your databse response properly using htmlentities().
$sql = 'SELECT row_with_text FROM your_table';
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
echo htmlentities($result['row_with_text']);
phpMyAdmin does the escaping for you, but it's your responsibility to escape text for HTML in your application.
Related
I'm having a strange problem while trying to get some data out of a MySQL database using PHP. Not sure if it matters, but encoding on database, connection and PHP file are all UTF-8. Heres my code:
$testcode = "Unique12345 & TestName";
$sql="
Select
dw_test.testID,
dw_test.testText
From
dw_test
Where
dw_test.testCode = '".$testcode."'
";
if(!$qry = mysqli_query($link, $sql)) reporterror(mysqli_error($link), $sql, $_SERVER['SCRIPT_URL'], __FILE__, __LINE__);
if(mysqli_num_rows($qry)>0){
$test_array = mysqli_fetch_assoc($qry);
$resultTest = $test_array['testID'];
$testText = $test_array['testText'];
}else{
echo "Nothing found";
}
If I run that using PHP, it will say "Nothing found", but if I run it using Windows MySQL Workbench, it returns 1 record (the correct one). I suspect that it is the ampersand (&), because changing the query to something else that exists works fine.
I have tried escaping the & with a slash:
$testcode = str_replace("&","\&",$testcode);
and I have tried playing around with single and double quote combinations, but everything I try produces the same result
What am I doing wrong in my PHP? How come the Workbench tool works fine when using the same query?
I solved it!
I added this in front of the sql query:
$testcode = str_replace("&","&",$testcode);
Thanks for everyones help
I'm trying to output a simple list with all the usernames registered on a single e-mail address in our database. The SQL queries necessary for it shouldn't be too hard, but apparently they are too hard for me - here's my issue:
$sql = "SELECT emailaddress FROM ".db_prefix("accounts")." where acctid = '$mailid'";
$mailadress = db_query($sql);
That one's working just fine - I'm declaring mailid in a earlier part of the code, and with that query I can output the e-mail adress (for debugging) of the currently logged in user without any problems. Fine so far.
$sql = "SELECT name FROM ".db_prefix("accounts")." where emailadress ='$mailadress'";
$charakterliste = db_query($sql);
Here's the issue: $charakterliste seems to stay empty, even though I'm pretty sure my syntax is correct. var_dump() and print_r() don't return anything that would point towards the array/variable containing something.
I've double checked and executed a similar query directly in the SQL database and found no problems there - all the fields I'm calling do exist, and the DB connection is fine too. I guess something is wrong in my syntax for the second SQL query? I'd want to list all the names saved in the $charakterliste afterwards with a foreach loop, but as of now there doesn't seem to be anything to list saved in there, although there should be.
Thanks in advance!
Are you sure the column 'emailadress' exist?
Maybe it's 'emailaddress' with two 'd'?
According to your first line of code it should be 'emailaddress'.
$sql = "SELECT name FROM ".db_prefix("accounts")." where emailaddress ='$mailadress'";
$charakterliste = db_query($sql);
I found similar questions but can't solve my problem yet. Here is the relevant code:
$query = "SELECT * FROM conceptos WHERE descripcion = '$descripcion'";
if ($result = mysql_query($query,$connection)){
if (mysql_num_rows($result) > 0){
//Do something
} else {
die($query);
exit;
}
} else {
die(mysql_errno() . ' - ' . mysql_error());
exit;
}
I don't have problems with the connection or the permissions, because this code snippet is inside a loop and the other queries enter the "Do something" section. But when I take the echoed query and execute it in phpMyAdmin, it returns 1 value as expected. Why? What reasons can lead to this behavior? Thanks in advance for any advice.
I had this problem and found that it was because I junked up my database by copy/pasting directly to the database from MS Word. Pasting had inserted special slanted apostrophes that PHPMYADMIN could apparently parse but my php code could not. Once I replaced those with a standard single quote, all was well.
Try this "SELECT * FROM conceptos". If it's worked, you have bad query in "WHERE ..."
Are you sure your query is searching for the right description? The double quotes should expand all internal variables, but you do have single quotes as well in case there is a copying to stackoverflow issue.
This will ensure that the description is expanded in case.
$query = "SELECT * FROM conceptos WHERE descripcion = '" . $descripcion . "'";
Secondly, have you validated the variable contents you are using, as suggested by #crotos?
The mysql_ are also deprecated, so you should use PDO, or at the least, mysqli_.
You can try to setup the general query log of your mysql server and see what queries are really executed. See http://dev.mysql.com/doc/refman/5.1/en/query-log.html
Also, check your encodings. Maybe your mysql connection is in ISO8859-1 and your table fields are in UTF-8 (or the opposite). Do you have any accents or special characters in your data?
i also faced this problem and got it solved using:
mysqli_query($con,$query);
instead of
mysql_query($query);
coz its depreciated
source:
File Downloading error from database php
I am fetching data from a MySQL table to display it on a page. The script is displaying the information, but in my table normal quotes we're inserted as another type of quote characters such as. ( ’ ) and ( “ ” ) which are automatically formatted this way when something is typed in Microsoft Word 2010, which was used to type most of the entries in the table. So my guess are those are special characters. But whenever i test out displaying a field with actual single quotes ( ' ) and ( " " ) i receive a mysql_fetch_row expects parameter 1 to be a resource, boolean given error. This is the code i use:
$result = mysql_query("SELECT `question` FROM {$db_table_alt}");
while($field = mysql_fetch_row($result)) {
foreach($field as $fields) {
//build a unique section ID based on the ID that the Question belongs to
$uid = mysql_query("SELECT `id` FROM `questions` WHERE `question` LIKE '%$fields%'");
while($uidfield = mysql_fetch_row($uid)) {
But whenever i use this line
$fields = mysql_real_escape_string(stripslashes($fields));
The field with real quotes will display, but with forward slashes before the quote.
Can somebody help me find a solution to this please?
If mysql_fetch_row() is complaining about a boolean that means mysql_query either returned no rows or the SQL had an error (mysql_error() will tell you which).
If you're getting backslashes before the quotes in your returned data, then they are getting put in the database. That sounds like magic_quotes are enabled. You really want to turn that off as it's an obsolete and broken solution to a problem.
Also, I think you're going to have to learn about character encodings. A default MySQL install will be not be UTF8, I'm afraid, it will probably be ISO-8859-15. Word used to like writing text in Windows-1252 which is not the same. And then it gets more complicated with whatever browser, website and other things that talk to the database use. I believe PhpMyAdmin tries to run in UTF8, so data will get converted into your tables if they're not UTF8. This will also affect your queries looking for the "smart quotes".
You seem to have two distinct problems here.
One where $result is evaluating to a boolean, which means there is an error in the query generated (SELECT question FROM {$db_table_alt}). Try echoing that query out and manually running it. It may be that the table/view named by {$db_table_alt} does not exist.
The second is a string escaping problem. I expect the quotes are escaped in the database - using mysql_real_escape_string on the query will not alter whether the returned results are escaped or not.
Also, if your data in the database is escaped by slashes, you should read up on magic quotes and what to do about them: PHP docs on magic quotes. You should not have to do any string escaping when pulling data out of the DB.
[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.