I'm trying to write a PHP string to create an SQL statement which uses a variable for a field name after the WHERE clause. The problem is that it doesn't use the variable name, I'm not good with PHP so not sure if it's my string concatenation or something else... any help would be appreciated! I'm using PHP 5.5 with mysql, as mysqli isn't available with my current host.
echo $sql_subject;
$sqlString2 = "SELECT * FROM tableName WHERE ". $sql_subject . " = '$set'";
However it keeps outputting:
S
SELECT * FROM tableName WHERE '' = '1'
I know the $sql_subject has a value because it's printing above the SQL output... I'd like it to say:
SELECT * FROM tableName WHERE S = '1'
Thanks
Related
Let's assume we want to give an input so that the program understands a variable we use. For example:
$name=$_POST['name'];
$p='...';
$sqlLogin= "SELECT user_id FROM user WHERE username=' ".$name." ' ";
if the input is {$p} , then the variable is not printed , instead the result is:
SELECT user_id FROM user WHERE username='{$p}'
Is there a way for the program to understand {$p} as a variable (through input), like it does
when we write
$sqlLogin= "SELECT user_id FROM user WHERE username='{$p}'";
Just to prove the concept here:
$name = '{$p}';
$p= 'MYVALUE';
echo eval("return \"".eval("return 'SELECT * FROM tblname WHERE username =\'$name\'';").'";');
Result:
SELECT * FROM tblname WHERE username ='MYVALUE'
But try to avoid the use of eval();
Have a nice day;
You will need to use the eval() function because the variable is a string, so the code is treating it as such, but you want the string to be ran as code.
eval("$sqlLogin = \"SELECT user_id FROM user WHERE username='{$p}'\"")
I know how to select from a database, my question is i want to set a variable for a where clause in my query, so lets say select * FROM Foo WHERE A = '$a', but the variable has not been set previously and is from the table i am trying to select from.
So how would i do this.
PHP
$FC_ID = mysqli_real_escape_string($dbc,[]);
$FOOD_sel = $dbc->query("SELECT * FROM Food_Cat WHERE Food_Cat_ID = '$FC_ID'");
That is how far i have got so far.
Try to use sub query for that $FC_ID value
sub query method
$FC_ID = mysqli_real_escape_string($dbc,[]);
$FOOD_sel = $dbc->query("SELECT * FROM Food_Cat WHERE Food_Cat_ID = (select FC_ID from your table )");
I have a string in PHP like:
"1234,2345,4567,5676,234,12,78957".....
I want to extract these numbers in varchar(30) format and use them on a command like
SELECT * FROM TABLE_NUM WHERE ID LIKE '%NUM';
where NUM will have above mentioned 7 strings.
And if possible i would also like to restrict '%' in '%NUM' to 1-5 characters only i.e. the prefix should not be greater than 5 characters. Example NUM = 1234 and ID has (31234,5678956781234) it should only provide first one as result and not the other one.
Accordingly I will get a merged result of all matching rows.
How can I achieve this ?
Thank You!
If that string is coming from a column somewhere in the database, you should fix the schema. It's almost always a bad idea to design a schema where you have to process sub-columnar data.
If it's a string from outside the database and you just want to run queries based on the individual parts, you're probably better off using facilities outside of your DBMS to construct the queries.
For example, using bash under Linux:
pax> list="1234,2345,4567,5676,234,12,78957"
pax> for i in $(echo $list | sed 's/,/ /g'); do
...> echo mysql "\"SELECT * FROM TABLE_NUM WHERE ID LIKE '%$i'\""
...> done
mysql "SELECT * FROM TABLE_NUM WHERE ID LIKE '%1234'"
mysql "SELECT * FROM TABLE_NUM WHERE ID LIKE '%2345'"
mysql "SELECT * FROM TABLE_NUM WHERE ID LIKE '%4567'"
mysql "SELECT * FROM TABLE_NUM WHERE ID LIKE '%5676'"
mysql "SELECT * FROM TABLE_NUM WHERE ID LIKE '%234'"
mysql "SELECT * FROM TABLE_NUM WHERE ID LIKE '%12'"
mysql "SELECT * FROM TABLE_NUM WHERE ID LIKE '%78957'"
That script will echo the commands to do what you want (assuming mysql is the correct CLI interface to your DBMS) - simply remove the echo at the start to actually execute the commands.
For PHP (as per your question edit), you can use the explode function to split the string, something like:
$list = "1234,2345,4567,5676,234,12,78957";
$numbers = explode (",", $list);
then execute a query for each element of $numbers.
If what you're after is a single result set formed from all of those values, there are other ways to do it. One involves using the list to construct an "uber-query" string that will do all the work for you, then you execute it once.
Simply use an or clause to join the different "sub" queries into one (pseudo-code):
$query = "select * from table_num"
$joiner = " where"
for each $element in $list:
$query = $query + $joiner + "id like '%" + $element + "'"
$joiner = " or"
execute_sql $query
That ends up giving you the query string:
SELECT * FROM TABLE_NUM
WHERE ID LIKE '%1234'
OR ID LIKE '%2345'
:
OR ID LIKE '%78957'
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.
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.