Returning a field with an ampersand - php

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

Related

PHP PDO query not inserting - Error HY093

After a lot of searching the web, the times I see this error, it looks really scenario specific. So far, I haven't found one that matched my scenario. I think my issue is coming from a prepared statement with spatial data type params.
The way I'm executing my code is:
$sql = $conn->prepare("INSERT INTO states(`name`, `poly`) VALUES(':name',GeomFromText('GEOMETRYCOLLECTION(:coords)'));");
$res = $sql->execute(['name'=>$name, 'coords'=>$coords]);
if($res){
echo "... Successfully Inserted<br><br>";
}
else{
echo "... Failed<br><br>";
print_r($sql->errorInfo());
echo "<br><br>";
}
The above is failing. The connection to the database has been tested. Since these are rather large geometry sets, instead of pasting my code, I'll show how I verified my SQL:
Dumping a raw SQL file and copy/pasting the SQL into a phpMyAdmin window, everything inserted just fine.
$sqlStr = "INSERT INTO states(`name`, `poly`) VALUES('$name',GeomFromText('GEOMETRYCOLLECTION($coords)'));";
$check = file_put_contents('./states/'.$name.'2.sql', $sqlStr);
So it's because of this, that I believe my sql is correct, but it my problem is likely due to the prepare/execute portion somehow. I'm not sure if spatial data types can't be assigned like this?
Edit
I also want to note that I am on PHP version 5.5.9 and I've executed queries in the original method, with the params in the execute just fine.
There's no way the code at the end could be working. Parameters in the query must not be put inside quotes.
Since GEOMETRYCOLLECTION(:coords) has to be in a string, you need to use CONCAT() to create this string.
$sql = $conn->prepare("
INSERT INTO states(`name`, `poly`)
VALUES(:name,GeomFromText(CONCAT('GEOMETRYCOLLECTION(', :coords, ')')));");

Query works in phpmyadmin but not in PHP script

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

sql query with LIKE

I have a weird problem please take a look at this query:
select * from myfriend where name like "%n%";
when execute this query on phpMyAdmin the query returned correct results, but when execute it using php no result returned.
please note this query executed in drupal 6.
what is the problem with char "n" and PHP?
Percent signs are used as placeholders in Drupal 6 queries, so you need to escape them:
$query = db_query('select * from myfriend where name like "%%n%%"');
$searchChar = "n";
$query = "SELECT * FROM `myfriend` WHERE `name` LIKE '%" . $searchChar . "%'";
Then use the $query variable in your statement.
Eg:
$mysql->query($query);
mysql_query($query);
Your query is perfect. Give some brief on it. You can check if your connection of database from php to mysql is correct. You can echo that query from php file and run into phpmyadmin if that gives correct output then surely database connectivity problem will be there.
There is absolutely no issues with any character in php.

SQLSRV with Linked Server

My issues basically revolves around me needing/preferring to use PHP's sqlsrv to access a sql-server 2000 database. I've worked on the project already using that with a sql server 2005 to run all the queries through and switching to something like the ODBC PHP drivers would be a pretty big headache right now. So now I have the original SQL Server 2000 database and 2005 installed on the same computer and I've created a linked server between the 2. Testing it out in Management Studio Express worked by running a simple query to one of the tables.
Now, I'm using the exact same query in PHP using sqlsrv_query and running into an error. My PHP code to test this out looks like this
$connectionOptions = array("UID"=>"user","PWD"=>"password");
$res = sqlsrv_connect("(local)\SQLExpress", $connectionOptions);
if(!$res) die("ERRORS : " . print_r(sqlsrv_errors()));
echo "SELECT * FROM [ServerName].DB.dbo.Table<br/>";
$res = sqlsrv_query($res,"SELECT * FROM [ServerName].DB.dbo.Table");
if($res===false){
die("ERRORS : " . print_r(sqlsrv_errors()));
}else{
var_dump($res);
$ary = sqlsrv_fetch_array($res);
}
var_dump($ary);
echo "<hr>";
var_dump(sqlsrv_errors());
The problem with this code is that the result of of sqlsrv_query doesn't return false but returns resource(11) of type unknown. So running fetch_array on that result tells me that an invalid parameter was passed to sqlsrv_fetch_array. I'm not sure what to do at this point. Is there just a problem running a query on a linked server through sqlsrv?
seems no error in your code.
Please try the fetch_array in a loop and update the result.
while($row = sqlsrv_fetch_array($result))
{
echo($row['field_name']);
}
also remove var_dump($ary);
Usually even if there is any error in the data display using '$row', the error message will show problem with 'sqlsrv_fetch_array'.
Well I figured out the problem. In my haste to make some code to test out whether or not the linked server worked, I just used the same variable name for the result of sqlsrv_connect and sqlsrv_query. Turns out, that was the whole problem. I switched the variable names so that the connection object is $Link and the query stays as $res. Now, I get the access to the database that I was trying to get through 2005 into 2000. So in the future, I definitely will name my variables a bit more carefully so I don't bang my head against the wall for hours.

mysql: not able to retrieve data which is in between <> symbols

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.

Categories