PHP Printing a string with multiple single quotes - php

So I'm having an issue that seems like it should be a pretty simple fix but I can't seem to figure it out.
I'm using prepared statements to query data from my SQL and the return is correct. I have var_dumped the result and confirmed the the information is there.
The table shows this: 2 'all of the way'
The array variable shows this: 2 \'all of the way\'
But when I echo it to the page, I see this: 2
I have tried htmlspecialchars, htmlentities, addslashes, stripslashes and a few combinations of those. Is there a function I'm missing here? Google isn't really helpful because the words to describe the problem are pretty generic.
Thanks in advance!
EDIT
Sorry - didn't add my code because I assumed it was a function I wasn't familiar with. Here it is.
$Res = $db -> query("SELECT * FROM 01_02_item WHERE ParID = $ParID AND active = 1 ORDER BY OrderID") -> fetchAll(PDO::FETCH_ASSOC);
if(empty($Res[0])) $return = "<span class = 'nodata'>No data</span>";
foreach($Res as $r){
$id = $r['id'];
$name = htmlspecialchars($r['Name']);
$title = stripslashes(htmlspecialchars($r['Description']));
$return .= "<li href = '$id' title = '$title' name = '$name'>$name</li>";
}
return $return;

By default htmlspecialchars() doesn't escape single quotes.
You should use htmlspecialchars('foobar', ENT_QUOTES).

Related

PHP issues with explode() and SQL query

I have a code in PHP like the next:
//$menutype is defined in this point, and no problem with it
$sql = "SELECT struct FROM menutype WHERE id=$menutype;";
$result = mysql_query($sql);
list($struct) = mysql_fetch_row($result);
$menu = explode("\n", $struct); //Explode to make an array with each line
foreach ($menu as $index => $value)
{
//$barid is defined in the top of the document and no issue with it
creatabla($barid, $value);
}
function creatabla($barid, $tipo)
{
$tipo = trim($tipo, ' '); //trim to delete unwanted spaces
$sql = "SELECT name FROM products WHERE tipo LIKE '%$tipo%' AND restaurante='$barid';";
$result = mysql_query($sql);
while(list($name) = mysql_fetch_row($result))
{
echo "$name";
}
}
Similar 'struct' row struct:
Line1
Line2
Line3
Line4AndLastLine
No car return after Last Line.
Well, the code usually works fine, but If I modify the 'Struct' row, some lines won't be read fine, so I usually need to edit the struct row in the advaced editor of the phpmyadmin.
What can I do to solve this issue? Can I try other kind of filter in the sql statement? What can I do to improve the trim or the explode function to solve this issue?
Thanks you to all in advance.
I think I'm starting to understand the issue and I'm guessing you're right - I'm guessing there is a \r character on the end.
Right now you are calling this:
trim($tipo, ' ');
That deletes ONLY spaces. If you change it to simply:
trim($tipo);
Then it will delete a lot more types of whitespace, including (but not limited to) the \r character.
See HERE for more information on the trim() function.

Can't $_GET contents of field using quoteid

I am sending myself crazy figuring out what the issue is with the following code. All names within the database are exact as I have them here however I can't seem to get the info from the quote using $quoteid however when I type in an id static e.g. quoteid = 12 I can filter through the data.
Obviously this isn't ideal.
<?php
$quoteid = $_GET["quoteid"];
if ($_GET['quoteid']) {
$quoteid = $_GET["quoteid"];
}
$quote = $db->getRow("SELECT * FROM quotes WHERE quoteid = $quoteid");
?>
Html
<h1><?php echo $quote->description;?></h1>
Any help would be greatly appreciated.
Thanks,
Melissa
Note that you need to put the PHP variables inside single quotes when writing SQL queries. Do it like in the example:
$quote = $db->getRow("SELECT * FROM quotes WHERE quoteid = '$quoteid'");
why you getting again and again $_GET["quoteid"] and also use single for variable when writing SQL queries
<?php
$quoteid = $_GET["quoteid"];
if (!empty($quoteid)) {
$quote = $db->getRow("SELECT * FROM quotes WHERE quoteid = '$quoteid'");
}
else {
echo 'quote id is empty';
}
?>
also use mysql_real_string_escape() to prevent sql injection
You should do the following... basic debugging.
print_r or var_dump for $_GET to see if and how "quoteid" is set up
in the $_GET superglobal
echo your SQL (instead of mysql_query just echo it) and run it in
phpmyadmin if it seems ok -- you might have something you missed out
somewhere
That way you should be able to figure out your issue faster
there is mistake in query syntax with $quoteid variable. you should use this one-
global $db;
$quote = $db->get_row("SELECT * FROM quotes WHERE quoteid ='".$quoteid."'");

Possible to use php tag inside query string?

I have multiple values passed through a POST form (from multiple check boxes of previous page) and I stored them into an array $vals. Now I want to write a query string (in a while loop) that generates a slightly different query depending on how far in the loop it has been.
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>
But it doesn't seem to work this way? I thought that by having double quotes for query, the
echo $vals[$i]
would generate the actual value of the current index in $vals[$i] and not the literal string? Is this what's happening? Can I not have php inside a query string that the mysql servers would accept?
lets just say i have a fooID in my server table that is '12345'. Even if I set $vals='12345' and write:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
it still doesn't work. I guess my general question would be: is it possible to write/get values of variables in a query string, and if not, is there another way around my situation? Any help is appreciated. Thanks!
You should not be placing the un-sanitized $_POSTed values into a SQL query. Look into using paramaterized arguments and mysqli.
You can output variables using the syntax:
$myVar = 'toast';
$combined = "I like $myVar";
However, this will not work as you would like for an array.
For an array, you'll want to look into using something like php's implode() to convert your array into a string first.
first of all never do queries in loop.
Second of all never use straight $_POST or $_GET or whatever client is passing in queries because you can be harmed by sql injections.wiki and also clearing data for mysql in php
ok so how it should be done (i am saying only about first one. second one i dont know how to make it without oop ).
<?php
$vals=($_POST['selectedIDs']);
$vals = implode(',',$vals);
$query = "SELECT * FROM List foo WHERE foo.fooID IN ($vals)";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_row($result)) {
echo "YES IT WORKS!";
var_dump($row); //you will see all the data in one row
}
}?>
You have an extra echo in your SQL string:
$query = "SELECT * FROM List foo WHERE foo.fooID = echo $vals[$i]";
It should be:
$query = "SELECT * FROM List foo WHERE foo.fooID = $vals[$i]";
Generally, it's a BAD idea to construct SQL strings from user input. Use prepared statements instead. Check here for more info on prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php
Thanks you guys for the advice but it turned out, my code didn't execute correctly because of a syntax error (and the extra echo statement). my original code was missing quotation marks around $vals[$i]. This is a mysql syntax mistake because it didn't accept foo.fooID=12345 but did for foo.fooID='12345'. Here is the final code that solved it
<?php
$vals=($_POST['selectedIDs']);
$i=0;
while($vals[$i] != NULL){
$query = "SELECT * FROM List foo WHERE foo.fooID = '$vals[$i]'";
$result = mysqli_query($link, $query);
if($result) echo "YES IT WORKS!";
$i += 1;
}?>

PHP Query Not Understanding Integer

Here's my code:
function display_name1($s){
global $db;
$query1 = 'SELECT Name From Drink where P_Key = $s';
$r = $db->prepare($query1);
$r->execute();
$result = $r->fetchColumn();
return $result;
}
$s contains the result returned from the P_Key, an auto incremented column. I want to be able to give the query the P_Key and it will return whatever variable from that row I want. For some reason, this isn't working. It returns nothing. Now if I return $s, then it does display the numbers like it should, so the problem isn't with the $s variable itself. If I take the $s out of the query, and replace it with a number, then it returns the name of the drink just like it should, so the problem isn't with the database or the query. The problem seems to be that $s is being interpreted incorrectly.
I've tried converting it to an integer ahead of putting it into the query, no dice. Any ideas?
Try to use double quotes.Single quote didn't interpret the variables."SELECT Name From Drink where P_Key = $s"
Reference: PHP String Parsing
use like this
"SELECT Name From Drink where P_Key = ".$s.""
you can find difference using echo $query1

while loop not working for acessing sql records

I am passing a string to this file -txtname- (string separated by spaces) and saparate each word and then pass it to the function subtoken() that should fetch the corresponding words from the database, having two attributes-rootwords and example,but subtoken() function executes only once and exits.
$counter=0;
$string = $_REQUEST['txtname'];
$token = strtok($string, ' ');
while ($token != false)
{echo $counter;
subtoken($token,$counter);
$counter++;
$token = strtok(' ');
}
function subtoken($fname,$counter)
{
$row ="";
$result="";
$result = mysql_query('SELECT * FROM hindi WHERE rootwords LIKE \'%:'.$fname.':%\'' );
while($row = mysql_fetch_array($result))
{
$temp=$row['rootwords'];
$token2 = strtok($temp, ':');
echo $token2 ;
while($token2!=false)
{
echo $token2."<br/>" ;
$token2=strtok(':');
}
}
}
mysql_close($con);
The double usage of strtok will prevent the "main" loop to properly process all tokens from the original $string. You simply can't have more than one "open" strtok use at the same time.
Original suspect was your query, that it just doesn't select anything. Try printing the SQL statement, then executing that statement directly (e.g. via phpmyadmin)
// insert this line:
echo(
'SELECT * FROM hindi '.
'WHERE rootwords LIKE \'%:'.$fname.':%\'');
// just before the actual query execution
$result = mysql_query(
'SELECT * FROM hindi '.
'WHERE rootwords LIKE \'%:'.$fname.':%\'' );
From my experience, echo'ing as much data as possible early on while debugging is one of the best tools to easily spot errors.
See also: http://nl2.php.net/mysql_fetch_array
mysql_fetch_array needs a second parameter to work correctly.
Replace mysql_fetch_array with mysql_fetch_row. Or mysql_fetch_assoc if you want to reference to the columns by name.
May be you have some error/warning? Is error_reporting set to E_ALL and display_errors to "On"?
It seems that strtok() has only one pointer. So, when you ended with it in function, you need to reinitialise $token = strtok($string, ' ');? dut I am not sure. I think it would be better if you used explode() function.

Categories