Problem with PHP query

I’m running this:

$stmt = $pdo->query( $sql); // I substitute $sql1 and $sql2 to test

while** ($row = $stmt->fetch())
{
echo** $row[ ‘name’ ] . “\n” ;
}

It works fine if I set the $sql using this line: $sql1= “select * from counties where state_id = 1” ;

But if I concatenate the state_id value using this line: $sql2 = "SELECT * FROM counties where state_id = " . $mystate; it fails.

Both look exactly the same when output to the page using echo.

Here’s the output:

SQL1: select * from counties where state_id = 1

SQL2: select * from counties where state_id = 1

I’m stumped. Any thoughts?

Variables have no business whatsoever being in a query. You need to use Prepared Statements. This tutorial will get you going.
https://phpdelusions.net/pdo

1 Like

I agree 100% with @benanamen: you should use prepared statements.

The value in the variable probably contains some additional characters - white-space, non-printing, or html markup. I’m guessing a new-line \n, since one is being concatenated to a different value in the posted code. What does var_dump($mystate); show?

1 Like

Prepared statements do not resolve the underlying issue. phdr is on the right track. When I echo the length of the strings one is 97 and the other is 186. If I surround $sql1 with quotes there is no content displayed yet somehow the string is long than it is displaying. I’ve tried preg_replace( “/[^a-zA-Z0-9]/” , “” , $sql1) but that only gets the string down to 146 characters. How can I truly see what’s in this string? If it’s not working it won’t help to pass it to a stored procedure.

The issue is likely because I am trying to get a javascript value to pass and using the following to get it:

ob_start();
echo **“document.writeln(state.value);”; //surrounded by script tags
$mystate = ob_get_contents();
ob_end_clean();

Is there a better way to do this?

phdr, It shows String 187.

Javascript is executed in the browser. Php is executed on the server when the page is requested. To get a value from javascript to the server, you must make a http get or post method request.

Actually I don’t, I was able to get the value using

document.writeln(state.value);" surrounded by script tags

I think the issue is the value includes the code which is running when I set the variable and included with it. Is there are way to strip this out?

So this looks like a dead end… how would I return a single value from a database using ajax when a dropdown option is selected?

Sponsor our Newsletter | Privacy Policy | Terms of Service