PHP mysql SELECT QUERY with an Or - php

mysql_query("SELECT * FROM foo WHERE id ='$foo' OR id = '$foo2");
This doesn't work.
Basically, I want to be able to select it where the id is one variable's value OR another one's.
Thanks.
EDIT: The ID column is numerical.

As others have said and you confirmed, the problem is that you are using string literals to compare to a numeric column. To have it work, the query should look like
mysql_query("SELECT * FROM foo WHERE id =$foo OR id = $foo2");
However, this solution has very very bad code smell!
First off, this is why IN exists: to be able to write
mysql_query("SELECT * FROM foo WHERE id IN ($foo, $foo2)");
And second, are you injecting unescaped strings into your query? If you are, your code is vulnerable to sql injection! Escape and quote your variables to be safe, like this (in the general case):
$query = sprintf("SELECT * FROM foo WHERE id IN ('%s', '%s')",
mysql_real_escape_string($foo),
mysql_real_escape_string($foo2));
mysql_query($query);
or alternatively like this, since in this specific scenario you know we 're talking about integer values:
$query = sprintf("SELECT * FROM foo WHERE id IN (%s, %s)",
intval($foo), intval($foo2));
mysql_query($query);
Footnote: I am aware that when using sprintf like this, one could also handle integer values by just using %d instead if %s as the format specifier. However, I believe that proving you are correctly escaping variables should be possible by just looking at one place (the parameter list) instead of multiple places (did I use intval on the variable? or maybe I did not, but I 'm using %d in the format string so I 'm still OK?). It may sound counter-intuitive, but it's more robust in the face of modifications.

I think you forgot the last ' character
mysql_query("SELECT * FROM foo WHERE id ='$foo' OR id = '$foo2'");
but because the id column is numerical, you should use:
mysql_query("SELECT * FROM foo WHERE id = $foo OR id = $foo2");

Try this:
mysql_query(sprintf("SELECT * FROM foo WHERE id = %s OR id = %s", $foo, $foo2));
I recommend you use mysql_error() for get mysql errors(if exists).
mysql_query( .. ) or die('Erro:'.mysql_error());
the mysql_error returns the last error occurred in mysql.

Related

Is it possible to use a $variable instead of 'row.table' in a mysql query?

For example:
$sql = "SELECT * FROM purch_inv WHERE '".$anyrow."'='".$anyrecord."'";
or
$sql = "SELECT * FROM '".$table."' WHERE 'rowabc'='".$anyrecord."'";
I have been trying this but it is not working, any ideas?
In php you could use variables in double quotes (ex.)
$name = 'John';
$var = "Hello $name!";
It shows: Hello John.
With single quotes (ex.)
$name = 'John';
$var = 'Hello $name!';
It shows: Hello $name.
Single-quotes mark a string literal.
But you want identfiers;
SELECT * FROM identifier1 WHERE identifier2='stringliteral'
a table name is an identifier. Identifiers
always can (and sometimes must) be wrapped in backticks.
SELECT x,y,z FROM `foo`
When I said a table name is an identifier, that wasn't entirely correct. In SELECT ... FROM foo foo is a name; it just so happens to be comprised of only one identifier, which is the table name.
There can be compound or multiple-part names, consisting of multiple identifiers connected via a dot between the parts. In that case you can (or must) wrap each single identifier in backticks; not the the whole name
SELECT x,y,z FROM `mydatabase`.`foo`
The fields you select (i.e. x,y and z in this case) are also names; so the same rules apply
SELECT `x`,`y`,`z` FROM `mydatabase`.`foo`
and again, in case you have multipart names you have to wrap each identifier individually in backticks, not the whole name
SELECT
`foo`.`x`,
`bar`.`x`,
`foo`.`y`,
`bar`.`z`
FROM
`foo`
JOIN
`bar`
ON
`foo`.`x`>`bar`.`y`
So, when do you use single quotes?
When you want a literal string in your query, like e.g.
SELECT x,y FROM foo WHERE y='abc'
this tells the MySQL parser that you want to compare the value of the field y to the string (literal) abc while
SELECT x,y FROM foo WHERE y=`abc`
would compare the value of the field y to the value of the field abc (which in my example doesn't exists and would therefore raise an error)
Full circle back to your question
$sql = "SELECT * FROM `$table` WHERE `rowabc`='$anyrecord'";
But please keep a good eye on http://docs.php.net/security.database.sql-injection regarding $anyrecord.
And make sure it is you (not the user) who is in control of $table.
yes you can
but you can't qoute the table name and column name
$sql="SELECT * FROM ".$table." WHERE rowabc='".$anyrecord."'";
the other example should be like this
$sql="SELECT * FROM purch_inv WHERE ".$anyrow."='".$anyrecord."'";
Obviously you need to think about SQL injection with the variables getting passed into your select query! So because table and column names cannot be replaced by parameters in PDO, you could use a function to create a whitelist of table names to pass into your query, then use a function with PDO to execute the statement:
$myWhitelist = array('table1', ...)
$myTable= array_intersect_keys($table1, array_flip($whitelist));
So now $table1 is safe to pass into your select function:
function select($conn, $table1, $someColumn) {
$myvar = $conn->prepare("SELECT FROM ".$table1." WHERE id = :someColumn");
$myvar->bindParam(":someColumn", $someColumn, PDO::PARAM_INT);
$myvar->execute();
if ($myvar->rowCount() > 0) {
return true;
} else {
return false;
}
}

passing variable with multiple values seperated by comma to sql statement through PHP

I've looked all over the interwebs, and cannot find that simple answer I'm looking for - possibly because it doesn't exist, but.. possibly because I don't know the correct terms to search for.
ok, so, i've got a variable - it's actaully a key value pair in an array that i'm passing into my function. the key is args[comments_mentioned] and the value is dynamically generated for me - it's ALWAYS going to be number, separated by commas (i.e. 1,2,3,4,5)
so, just to be super clear:
$args[comments_mentioned] == "1,2,3,4"; //could be any amount of number, not just 1,2,3,4,5
i'd like to pass this into a sql statement as a variable to use in an "IN" clause, like so:
$sr_sql = <<<SQL
SELECT *
FROM $wpdb->commentmeta
WHERE meta_value = %s
AND comment_ID in ($args[comments_mentioned])
ORDER BY meta_id DESC
SQL;
Then, Prepare it using the wordpress prepare and get results
$sr_query = $wpdb->prepare( $sr_sql, $args[user_id]) );
//receive the correct sql statement, and plug 'er in.
$sr_comment_rows = $wpdb->get_results($sr_query);
and run my foreach loop:
foreach ($sr_comment_rows as $sr_comment) {
$sResults .= 'do something with $sr_comment';
}
now, i realize the code above won't work - i can't just pass the variable in there like that. BUT, i can't pass it as a string (%s), because it wraps it in '1,2,3,45', and so it looks for the entire string, and not each number. I can't pass it as an int (%d), because of the commas...
In other posts, they mentioned create a temp table or variable, but, i'm not sure if that's the correct way to do it in mysql, or how to reference it once I do.
so, how do I do this? preference for actual code that works ;)
Thank you for reading and helping out!
One option, if you cannot normalize your data, is to enclose your string in commas such that it be ",1,2,3,4," and then you could do:
AND LOCATE( CONCAT(',',comment_ID,',') , ($args[comments_mentioned]) )
which will match if it finds a eg. ',3,' in ',1,2,3,4,' (Using 3 as an example)
I believe this should be enough:
$params = $args[comments_mentioned];
$table = $wpdb->commentmeta;
$sr_sql = "
SELECT *
FROM $table
WHERE meta_value = %s
AND comment_ID in ($params)
ORDER BY meta_id DESC
";
It will be result something like:
SELECT *
FROM table_on_variable
WHERE meta_value = %s
AND comment_ID in (1,2,3,4)
ORDER BY meta_id DESC
If your mainly issue is regarding the in clause, so you will not have problems if you use double quotes and single variable as illustrated above.

Counting rows with variables in where clause

I'm having trouble using variables in my SQL WHERE clause. I'm getting this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
result resource
The code is:
$sql3= mysql_query("SELECT COUNT($ww) FROM data WHERE $".$ww." = ".$weeknumber." ");
What am I doing wrong?
Why don't you count the table column by putting the columns name in your COUNT(column_name)?
Like so:
$sql3= mysql_query("SELECT COUNT(week_num) as wknum FROM data WHERE '$ww' = '$weeknumber'");
$counted_weeks["week_num"]
// $counted_weeks["week_num"] will output your sum
//week_num would be a column name from your "data" table
I recommend looking at this link. As #Crontab mentioned I am not sure why you have a dollar sign in front of your where clause.
A couple other things to point out:
As it says in the link, you will need to make sure the query text is properly escaped. Also, If I'm not mistaken (not familiar with PHP) do you need to explicitly concatenate the text instead of just using quotes? (i.e. instead of "SELECT ... " ... " do you need to do "SELECT ... " + " ... ")
php string formatting is perfect here, take your messy confusing concat string and make it clean and readable!
$sql3= mysql_query(sprintf("SELECT COUNT(%s) FROM data WHERE %s=%d", $ww, $ww, $weeknumber));
Assuming that $ww is a valid column name and $weekNumber is an integer, this should work:
$query = "SELECT COUNT(*) AS cnt FROM data WHERE $ww = '$weekNumber'";
$rs = mysql_query($query);
$r = mysql_fetch_assoc($rs);
echo "Count: {$r['cnt']}";
I am guessing $ww is referring to a column name. $weekNumber is obviously the value. In that case, your SQL query should look like this:
$sql3= mysql_query("SELECT COUNT(".$ww.") FROM data WHERE ".$ww." = ".$weeknumber." ");
I'm not a PHP guy, but I'm assuming you have the correct PHP syntax.

How do i select multiple rows which match the value of an item in an array?

I have written a php script that returns an arbitrary number of specific ids (which are in the format of numbers) in an array. I would like to make a new query that selects each row from a table that belongs to each id. I know i can do 1 query to get one row with the matching id. But i would like to do this all in one query. Here is my code:
$id = array(1,4,7,3,11,120); // The array containing the ids
$query = mysql_query("SELECT *
FROM posts
WHERE id = '$id[0]'");
// I would like to Do this for each id in the array and return it as one group of rows.`
I think you want the IN clause:
$idList = implode(",", $id);
SELECT *
FROM posts
WHERE id IN ( $idList );
The implode() function will turn your array of numbers into a comma-separated string of those same values. When you use it as part of an IN clause, it tells the database to use those values as a lookup table to match id against.
Standard Disclaimer/Warning:
As with any SQL query, you really shouldn't be directly concatenating variables into the query string. You're just opening yourself up to SQL injection. Use prepared/parameterized statements instead.
Use PHP's implode function to convert the array into a comma separated value string.
Then, you can use the SQL IN clause to run a single SQL statement containing the values associated with the ids you captured from PHP:
$id = array(1,4,7,3,11,120);
$csv = implode(',', $id);
$query = sprintf("SELECT *
FROM posts
WHERE id IN (%s)",
mysql_real_escape_string($csv));
$result = mysql_query($query)
I omitted the single quotes because they aren't necessary when dealing with numeric values in SQL. If the id values were strings, each would have to be encapsulated inside of single quotes.
What you want is SQL's IN clause.
SELECT * FROM posts WHERE id IN (1, 4, 7, 11, 120)
In PHP, you'll probably want something like:
$query = mysql_query(sprintf("SELECT * FROM posts WHERE id IN (%s)", implode(',', $id)));
Obviously, that's assuming you know you have integer values for $id, and that the values for $id didn't come from the user (that is, they should be sanitized). To be safe, you really ought to do something like:
$ids = implode(',', array_map('mysql_real_escape_string', $id));
$query = mysql_query("SELECT * FROM posts WHERE id IN ($ids)");
And if $id is dynamically generated, don't forget to put something in that IN clause, because SELECT * FROM foo WHERE bar IN () will give you an error. I generally make sure to set my IN-clause variables to 0, since IN (0) is good, and primary keys are pretty much never 0.

Coding of parameter-value for SELECT in PHP-MySQL

Alt A below is a statement from a php-mysql tutorial. It works as it should.
I found the id-value rather obfuscated and tested alt B. This also worked!
What is the point with the id-value of alt A?
MySQL 5.0.51, PHP 5.2.6
// Alt A :
$sql = "SELECT * FROM example WHERE id = '".$q."'";
// Alt B :
$sql = "SELECT * FROM example WHERE id = $q";
This are just two different approaches to building a string from static and variable data.
Alternative A uses concatenation, or the joining of string and variable tokens using the concatenation operator.
Alternative B uses variable expansion, wherein the variables inside a double-quote-delimited string are expanded to their values at evaluation time.
Neither is necessarily better or preferred, but if you have to have single-quote-delimited strings, for example, then you would need to use alternative A.
Of course, neither of these is preferable to building SQL queries with bound parameters, as not doing so leaves you vulnerable to SQL injection attacks.
Theres two reasons to use the example in 'Alt A'. First is if the string is enclosed in single quotes '', the variable's name will be used in the string instead of it's value.
$id = 7;
'SELECT * FROM table WHERE id = $id' //works out to: WHERE id = $id
"SELECT * FROM table WHERE id = $id" //works out to: WHERE id = 7
Secondly, it's useful to combine strings with the results of a function call.
"SELECT * FROM table WHERE id = '".getPrimaryId()."'"
Outside of what has already been said I've found it best practice, if I'm writing a query, to write it as so:
$sql = "SELECT * FROM table WHERE uid=" . $uid . " LIMIT 1";
The reason for writing SQL like this is that 1. MySQL query doesn't have to parse the PHP variables in the Query and 2 you now easily read and manage the query.
When PHP communicates with MySQL, it is actually (in essence) two languages communicating with each other. This means that a string will be processed by the first language before being sent to the other. It also means that it is important to think in terms of the receiving language
In this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = $q";<br/>
you are telling MySQL to
"SELECT * FROM example1 WHERE id = some_name.
In this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = '$q'";<br/>
and this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = '".$q."'";<br/>
you are telling MySQL to
"SELECT * FROM example1 WHERE id = 'some_name'.
The first example should cause an error as some_name is not a valid part of a MySQL query (in that context). On the other hand, the next two will work fine, because MySQL will look for the String "some_name".
You can also do this:
$sql="SELECT * FROM exempel WHERE id = {$q}";
which is useful for setting off things like:
$sql="SELECT * FROM exempel WHERE id = {$row[id]}";
in 'alt B', $q must be an int or float or other numeric
in 'alt A', $q can be anything a string, int, etc.
The single quote makes that possible. It's just hard to see sometimes if you are looking at it for the first time.

Categories