PHP mysql_query() Select with CONCATENATION - php

I have the following php code:
mysql_query("SELECT a FROM b WHERE b.c = '".$_REQUEST['companyName']."'");
I also have a string:
$mynumbers = "AND b.question_code IN (1);";
How can I combine this string withing the mysql_query()?
Thanks,

mysql_query("SELECT a FROM b WHERE b.c = '".$_REQUEST['companyName']."' " . $mynumbers);
But keep in mind that AND GROUP BY all_surveys.question_code IN (1); is incorrect sql and makes no sense.

You can also do like this if you want more simplicity;
$sql="SELECT a FROM b WHERE b.c = '".$_REQUEST['companyName']."'";
$sql.=$mynumbers;
echo $sql;
Also as zerkms said your sql seems to be incorrect

First is, you can not combine above two statements, the alternatively you can do like this-
//Here i assume that you want to concatenate 2nd condition on particular situation so you need to add if condition or else you can directly contcate it with "." (dot) operator.
$query = "SELECT a FROM b WHERE b.c = '".$_REQUEST['companyName']."'";
if(//your condition) $query .= "AND GROUP BY b.question_code IN (1);";
mysql_query($query);

Dont use AND before Group By
Try the following code,
$query = "SELECT a FROM b WHERE b.c = '".$_REQUEST['companyName']."'";
$query .= " GROUP BY b.question_code IN (1)"
mysql_query($query)

Related

How to add PHP variable in SELECT Query?

I have a problem in add value in SELECT query.
$sql=("SELECT `image` FROM `testtable`");
The output: 123.jpg
But I want output: 127.0.0.1/home/galery/123.jpg
So I tried:
$path='127.0.0.1/home/galery/';
.........
$sql=("SELECT $path+`image` FROM `testtable`");
But it's not working.
There are two ways to accomplish this.
Method 1:
Use string concatenation to join the path to the result from the SQL:
$path = '127.0.0.1/home/galery/';
$sql = "SELECT `image` FROM `testtable`";
// Run the query...
$result = $path . $sql;
In php, string concatenation is performed with the . operator. Also see here.
Method 2:
The second method is via the CONCAT SQL function:
$sql = "SELECT CONCAT('" . $path . "', `image`) FROM `testtable`";
Or:
$sql = "SELECT CONCAT('{$path}', `image`) FROM `testtable`";
See this question for the difference between these options.
$sql=("SELECT CONCAT('$path',`image`) FROM `testtable`");
Use concatenation like below....
$sql=("SELECT".$path."+image FROM test")
Here, text in double quotes are string

PHP how to print a query with SUM and math operators

I need to print a mysql (or better mysqli) query that contain math operators.
If I use a query like that
$sql = "SELECT SUM( `Home` + `Away`) AS Tot\n"
. "FROM `teams`\n"
. "WHERE `idteam` = \'Chelsea\'";
when I go to print the %result with mysql_result:
<?php echo mysql_result($result1,0); ?>
or with mysqli function:
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s \n",$row[0]);
it doesn't works.
The same code works if the Query ask to db just a simple information and not math operators like "SELECT SUM(a+b)*3"
Any ideas?
Thank you for support
try
$sql = "SELECT Home + Away AS Tot FROM teams WHERE idteam='Chelsea'";
SUM() is an aggregate function, your just adding 2 numbers
$sql = "SELECT SUM(Home + Away) AS Tot FROM teams WHERE idteam='Chelsea'"; Works for me. I think the problem is in your php try
echo mysql_result[0];
what if you try this?
$sql = "SELECT SUM(Home + Away) AS Tot FROM teams WHERE idteam='Chelsea'";
$res = mysql_query($sql);
while ($row = mysql_fetch_array($res))
{
echo $row["Tot"]."<br>";
}
(but this will print only one row)

using a php variable in the WHERE clause of a mysql query

I'm running a very simple query that I think should work. The only thing that I haven't done before is put a php variable in the WHERE clause of the query. The variable $X is a numerical value, say 100. When I run this query, I just get a value of 0 returned. Am I doing something obviously stupid?
SELECT generator_64k.n
FROM generator_64k
WHERE generator_64k.n<= '$X'
I've looked around the web and also tried this:
SELECT generator_64k.n
FROM generator_64k
WHERE generator_64k.n<= '" . $X . "'
But this also just returns 0.
Any ideas? Thanks in advance.
$query = "SELECT generator_64k.n FROM generator_64k WHERE generator_64k.n<= {$X};";
Try this one, or post your PHP code.
<?php
$X = 100;
$query = "SELECT n FROM generator_64k WHERE n <= $X";
$result = mysql_query($query);
if (!$result) {
echo ('Query error: ' . mysql_error());
}
E.g of php and using variables
$query = "select * from table1 where col1 <=" .$myVariable;
$result= mysql_query($query);
The mysql_query() function returns false on error (false == 0), otherwise, it returns a resource. mysql_query does not return the value from the result set. You must use mysql_fetch_assoc or something similar to fetch the rows from the result set.
Also, ensure that you wrap the query in double quotes so PHP can expand the variable $X.
Use mysql_error to fetch the error from the last call to mysql_query.
make it like this
$sql="select `username` from `users` where id='$newid';";
mysql_query($sql);
here $newid is the int value.
The symbol used before and after username, to get this you have to press the key just below esc .
You can't have ' around your numeric value. MySQL will treat it as string.
You should do this instead
" WHERE number <= " . (int)$val . " .. "
// or (but not recommended due to security problem)
" WHERE number <= $val "

php with SQL query

i have a problem with php in the following:
$sql = 'SELECT name FROM chiled WHERE `im` LIKE $id ';
$query = mysql_query( $sql );
$a=mysql_fetch_row($query);
echo $a[0];
there is error in mysql_fetch_row($query);
but if i do the following :
$sql = 'SELECT name FROM chiled WHERE `im` LIKE 1111 ';
$query = mysql_query( $sql );
$a=mysql_fetch_row($query);
echo $a[0];
it is working and prints the name
can you please tell me what is wrong?
Single quotes in PHP doesn't evaluate embedded variables - you need to use double quotes to do that. (See the "Single quoted" section of the PHP Strings manual page for more info..)
i.e.: $sql = "SELECT name FROM chiled WHERE 'im' LIKE $id ";
Or better still...
$sql = 'SELECT name FROM chiled WHERE im="' . mysql_real_escape_string($id) . '"';
(As you're not using the % in your like, you're presumably not attempting to do any form of pattern matching.)
Additionally, I'd recommend a read of the existing Best way to stop SQL Injection in PHP question/answers.
Are you sure you want to be using LIKE? It looks more to me like you want to see if im = $id. Also, make sure you're escaping your variables before using them in the query.
Edit
If you DO want to us LIKE, you probably want something like this:
$sql = "SELECT name FROM chiled WHERE `im` LIKE '%$id%' ";
which will find anywhere that the string $id is found in the im column.
You need to quote the variable after LIKE, like this:
$sql = "SELECT name FROM chiled WHERE im LIKE '$id'";
$query = mysql_query($sql);
$a = mysql_fetch_row($query);
echo $a[0];
// ....
Beside, you are using single quotes, Therefore, $id is not replaced for its value. Your query look like this:
SELECT name FROM chiled WHERE im LIKE $id;
$sql = "SELECT name FROM chiled WHERE `im` LIKE '$id' ";
change to double quotes - http://php.net/manual/en/language.types.string.php

Small Php and MySql problem

I have an array of ID:s, and the ID:s are in this format:
Bmw_330ci_89492822
So it's a string!
Now, I have this code to find whatever is in that array, in MySQL:
($solr_id_arr is the array I mentioned above, it contains string ID:s)
ex: $solr_id_arr[0] outputs Bmw_330ci_89492822
$solr_id_arr_imploded = implode(", ", $solr_id_arr);
$query = "SELECT * FROM my_table WHERE ad_id IN ('$solr_id_arr_imploded')";
$qry_result = mysql_query($query) or die(mysql_error());
Problem is this wont work because (I think) that there should be quotes around each of the imploded elements in order for MySQL to find the match. The field in MySQL I am matching is of type Varchar.
Here is the $query echoed:
SELECT * FROM my_table WHERE ad_id IN ('Bmw_m3_cool_565440282, Bmw_m5_839493889')
Do you have any other solutions for this, all I need is to find matches in MySQL which are inside this array!
Thanks
Don't surround the entire thing in quotes. It is looking for where ad_id is 'Bmw_m3_cool_565440282, test'
Use
SELECT * FROM my_table WHERE ad_id IN ('Bmw_m3_cool_565440282', 'test')
A quick fix would be to change:
//this
$solr_id_arr_imploded = implode(", ", $solr_id_arr);
//to this
$solr_id_arr_imploded = implode("', '", $solr_id_arr);
This one seems complicated but it's more safer and fastest one
function escaped($str)
{
return mysql_escape_string($str);
}
$arrayOfIds = array_map("escaped", $solr_id_arr);
$solr_id_arr_imploded = implode(", ", $arrayOfIds);
$query = "SELECT * FROM my_table WHERE ad_id IN ('$solr_id_arr_imploded')";
$qry_result = mysql_query($query) or die(mysql_error());
Simple switch to ', ' in implode():
implode("', '", $solr_id_arr);
This, together with the hardcoded quotes in the SQL string will format them as separate items.
Previous answers will work fine.
Just make sure the strings themselves do not contain quotes. If they do, escape each string before you do the implode().
If it were my code I'd write it like this:
$solr_id_arr_imploded = "'" . implode("', '", $solr_id_arr) . "'";
$query = "SELECT * FROM my_table WHERE ad_id IN ($solr_id_arr_imploded)";
$qry_result = mysql_query($query) or die(mysql_error());
...just because it keeps all the quoting work in one place. You might also want to make sure that the array isn't empty before entering this block of code. Otherwise the SELECT will match all empty ad_id's, which probably isn't what you wanted. We're also assuming that the elements of the array don't include any quote characters (or user-provided strings that haven't been sanity-checked).

Categories