comparision operation Sql query with php - php

$num=$_POST['data'];
$no = (int) $num;
$sql = "select * from uploads where id > '$no'"
The above query not working properly.It is displaying the values below the no.I think the problem with conversion.somebody please help to solve this problem

Try this code instead:
if ( empty( $_POST['data'] ) ){
// show error message
echo "No data received";
// use a default values
$num = 0;
}
else
$num=$_POST['data'];
$no = intval($num);
$sql = "select * from uploads where id > $no";
Try to use intval instead of casting to int

You have apostrophes around the value, so the values will be compared as strings, not numbers. The string value 10 for example is smaller than the string value 2.
Remove the apostrophes:
$sql = "select * from uploads where id > $no";

You have Sno = ..., it should be $no = .... It's a typo.
Then, numbers in query doesn't require apostrophes, so don't use them in this context.
You also had $_post instead of $_POST - it's another issue, variables in PHP are case-sensitive.

Try with this
$sql = "select * from uploads where id > ".$no;
and also put $_POST instead of $_post

$no = (int) $_POST['data']; //wrong variable declaration ?
$sql = "select * from uploads where id > $no";
Try this.
$_post replaced by $_POST
one variable instead of two

Related

Pass a PHP string in to SQL with multiple values?

I have a situation in some really old code of mine where I am trying to pass through the data from a string and do a DB query off of those values.
The data loads correctly if I set $hula = '7630' but when I set it to multiple values in a string like $hula = '7890, 5630' I get error (Message: db2_execute(): Statement Execute Failed)
I clearly know I am missing something here but I am CLEARLY not seeing it. Thanks
<?php
$hula = '7890, 5630';
$stmt = "SELECT TXLCT2, ZFDLDS FROM ".$ArEnviro>getDataLibFin().".TXPL6C2, ".
$ArEnviro->getDataLibFin().".HXPTABLD WHERE TXLCT2 = CFDECD AND CFDTCD = 'YCT2' AND TXLLV6 IN ? ORDER BY TXLCT2";
$preparedStmt = db_prepare($ArConnections->getDB2ConnResource(),$stmt);
$result = db_execute($preparedStmt, [$hula]);
while(($row = db_fetch_both($preparedStmt)) == true) {
echo('<option value="'.htmlspecialchars($row["TXLCT2"]).'">'.htmlspecialchars($row["TXLCT2"]).' - '.htmlspecialchars($row["ZFDLDS"]).'</option>');
}
?>
A simple change:
if TXLLV6 is integer:
$hula = '(7890, 5630)';
If it is varchar or any kind of string:
$hula = "('7890', '5630')";

Pulling data from mysql based on Array

I have a file file.php and inside my file I am using the code bellow to pull some data from my database and display some information.
My code is
$array = $_GET['theurl']; // My url looks like myfile.php?theurl=1,2,3 (id,s)
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sql);
$tc4a = mysql_fetch_assoc($rsdt4);
$mycomma4 = ",";
if ($tc4a['a_youtube'] == "#"){
}else{
while ($tc4 = mysql_fetch_assoc($rsdt4))
{
echo $tc4['a_youtube'];
echo ",";
}
}
I expect to echo the infos of the two id's (in array) inside my while function, but it returns the results only from the first.
Any ideas?
I am confusing on $sql :
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sql);
Can you take a look after changing below:
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sqlnt4);
First that's extremely vulnerable to security issues - I hope this isn't used in production and just for playing around.
I recommend switching to PDO, or at the very least securing your variables.
To put that array into the query, you need to implode it into a list, as such.
$list = implode(',', $array);
You can then use the list in the statement, which will look like 1,2,3.
Edit:
I've just realized your $array value isn't actually an array - have you missed code out or is it badly named?
mysql_fetch_assoc: "Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead." http://pt2.php.net/mysql_fetch_assoc
Try mysql_fetch_rows to return all matching rows into an array.

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;
}?>

Getting value from my sql data base using get method

I am getting values from mysql data base using get method i am passing survey_id and question_id from the url
like below
http://myserver.com/emrapp/surveyAnswersScreenOne.php?survey_id=1,question_id=1
but it is giving error
my php code is given below for fetching
$query = mysql_query("SELECT * from survey_Answers where survey_Id='".$survey_id."' AND question_Id='".$question_id"' ");
$rows = array();
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
echo json_encode($rows);
This line is having error,this:
$question_id"' "
should be
$question_id . "'"
You should be separating get variables with & not , in the url.
That's because you should use & instead of , between url parameters
http://myserver.com/emrapp/surveyAnswersScreenOne.php?survey_id=1&question_id=1
$survey_id = mysql_real_escape_string($_GET['survey_id']);
$question_id = mysql_real_escape_string($_GET['question_id']);
GET params are normally separated with & not ,. So your link should look more like this:
http://myserver.com/emrapp/surveyAnswersScreenOne.php?survey_id=1&question_id=1
Also, please note that GET variables are not automatically translated to PHP variables. You need to pull them from $_GET array:
$survey_id = $_GET['survey_id']
You does not pass value comma separated in url.You have use & in url like
http://myserver.com/emrapp/surveyAnswersScreenOne.php?survey_id=1&question_id=1
$query = mysql_query("SELECT * from survey_Answers where survey_Id='".$survey_id."' AND question_Id='".$question_id."' ");
A dot is missing!
URL and QUERY BOTH ARE WRONG
http://myserver.com/emrapp/surveyAnswersScreenOne.php?survey_id=1&question_id=1
AND
$question_id . "' "
$query = mysql_query("SELECT * from survey_Answers where survey_Id='".$survey_id."' AND question_Id='".$question_id"'");
you forgot the point for concatenating the string after $question_id -> this should fix your issue:
$query = mysql_query("SELECT * from survey_Answers where survey_Id='".$survey_id."' AND question_Id='".$question_id."'");
anyway,also consider sanitizing your url-inputs -> http://xkcd.com/327/

php counter increment error

As i am trying to increment the counter to plus 1 every time when the user clicks on the image. I have written the following code but it says some error "Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\tkboom\includes\core.php on line 72". Can anyone look into this where i made a mistake..
Actually i have created 2 php files one for incrementing the counter and one for displaying the counter. In core.php file i have written the function and for displaying the count i have created a file called view.php
core.php
function GenerateCount($id, $playCount) {
global $setting;
$counter_query = "SELECT hits FROM ava_games WHERE id=".$_GET['id']."";
$counter_res = mysql_query($counter_query);
while($counter_row = mysql_fetch_array($counter_res)){
$counter = $counter_row['hits'] + 1;
$update_counter_query = "UPDATE ava_games SET hits=".$counter." WHERE id=".$_GET['id']."";
$playCount = mysql_query($update_counter_query);
$playCount = $row['hits'];
}
return $playCount;
// Get count END
}
view.php
<?php
$sql = mysql_query("SELECT * FROM ava_games WHERE published=1 ORDER BY id desc LIMIT 30");
while($row = mysql_fetch_array($sql)) {
$url = GameUrl($row['id'], $row['seo_url'], $row['category_id']);
$name = shortenStr($row['name'], $template['module_max_chars']);
$playRt = GenerateRating($row['rating'], $row['homepage']);
$playCt = GenerateCount($row['id'], $row['hits']);
if ($setting['module_thumbs'] == 1) {
$image_url = GameImageUrl($row['image'], $row['import'], $row['url']);
$image = '<div class="homepage_game"><div class="home_game_image"><img src="'.$image_url.'" width= 180 height= 135/></div><div class="home_game_info"><div class="home_game_head">'.$name.'</div></div><div class="home_game_options"><img class="home_game_options_icon" src="'.$setting['site_url'].'/templates/hightek/images/joystick-icon.png" /> '.$playRt.' <b>|</b> '.$playCt.' plays </div></div>';
echo $image;
}
}
?>
That most likely means that there's an error in the sql statement. You can get more information about the error via mysql_error().
In its simplest form:
$counter_res = mysql_query($counter_query) or die(mysql_error());
(edit: ...simplest form, but with this approach you don't give the application a chance to react to the problem, "die" as in "dead". And mysql_error() can leak too much information to a user of your webservice/website, see https://www.owasp.org/index.php/Top_10_2007-Information_Leakage_and_Improper_Error_Handling)
Your code is also prone to
sql injections, because the $_GET parameter is put into the statement without sanitizing it first
race conditions because you have a compound operation consisting of one SELECT and one UPDATE without any locking mechanism.
This is because you get the error in your SQL query.
I'd change it a little bit:
$counter_query = 'SELECT hits FROM ava_games WHERE id = ' . (int)$_GET['id'];
to make sure you always compare id against integer value.
After all, this query does not look good. First point: why are you using two queries to increment a value? UPDATE ava_games SET hits=hits+1 WHERE id=".$_GET['id'].""should do this in one step. Second point: have you heard about SQL injections? Escape or cast $_GET['id'] to avoid surprises ;)
Convert the value in int first like that:
function GenerateCount($playCount) {
global $setting;
$counter_query = "SELECT hits FROM ava_games WHERE id=".$_GET['id']."";
$counter_res = mysql_query($counter_query);
while($counter_row = mysql_fetch_array($counter_res)){
$counter = intval($counter_row['hits']) + 1;
$update_counter_query = "UPDATE ava_games SET hits=".$counter." WHERE id=".$_GET['id']."";
$playCount = mysql_query($update_counter_query);
$playCount = $row['hits'];
}
return $playCount;
// Get count END
}
and check link:
Convert into int
If mysql_query returns a Boolean, your query failed.
Presuming id is the primary key, you can use the following function to update on a database level which will prevent race conditions:
function GenerateCount($playCount) {
global $setting;
$update_counter_query = "UPDATE ava_games SET hits=hits + 1 WHERE id=".intval($_GET['id'])."";
mysql_query($update_counter_query) or die(mysql_error());
$counter_query = "SELECT hits FROM ava_games WHERE id=".intval($_GET['id'])." LIMIT 1";
list($playCount) = mysql_fetch_row(mysql_query($counter_query));
return $playCount;
// Get count END
}
also note the intval() around the $_GET variable to prevent SQL injection

Categories