why i can't use this code ? and could anyone tell me what is the correct code ?
$lfr_prfid = "profile='$log_id'";
$lfrsql = "SELECT * FROM friends WHERE user2='$log_id' AND accepted='1'";
$lfrquery = mysqli_query($db_conx, $lfrsql);
while ($lfrrow = mysqli_fetch_array($lfrquery, MYSQLI_ASSOC)) {
$lfr_id = $lfrrow["id"];
$lfr_user1 = $lfrrow["user1"];
$lfr_user2 = $lfrrow["user2"];
$lfr_prfid += " OR profile='".$lfr_user1."'";
}
the last line i wrote this ( += ) and the code doesn't work so how can i do this in another way ? so i can use this in a SELECT statement .
$psql = "SELECT * FROM posts WHERE ".$lfr_prfid." ORDER BY postdate DESC LIMIT 0,20";
$pquery = mysqli_query($db_conx, $psql);
$lfr_prfid.=
Concatenate with . not with +. The + is concatenation in javascript.
so, in php: $myVar.= 'foo';
and in javascript: myVar+= 'foo';
Update based on your edit:
Please, DO NOT use that in a database query. Use prepared statements or your code is dangerous.
Change your code to:
$lfr_prfid .= " OR profile='".$lfr_user1."'";
Concatenation in PHP is done with ., not with += as you have written.
Hope this helps!
Related
I am working on a PHP file and getting via POST this string:
$temas = $_POST['temas']; //$temas = ".45.12.34"
Where each of the numbers should be the id for a table record.
And I have following query
$query = "SELECT * FROM tb_preguntas WHERE tema = '".$temas."'";
I need to put in the WHERE part of the query each of the received id
Something like that: ... WHERE tema = 45 OR tema = 12 OR tema = 34
Of course, on each execution the string changes.
I have tried using the PHP explode function, but I don't know how to implement the result in the query.
My answer won't differ too much from everyone else's but it is an answer to address SQL injection + a solution
$temas = implode(',', explode('.', $_POST['temas']));
$temas = trim($temas);
$res = $conn->prepare('select * from `tb_preguntas` WHERE `tema` in (:temas)');
$res->execute(array(':temas' => $temas));
here we use a prepared statement, now you're code is safe woop woop
As suggested above you can use the IN() function of mysql, however you have to remove the first period '.' and change the rest to commas ','.
$query = "SELECT * FROM `tb_preguntas` WHERE `tema` IN('".str_replace('.',',',trim($temas,'.'))."') ";
best case scenario
$temas = implode(',', explode( '.', $_POST['temas']));
$query = "select * from tb_preguntas WHERE tema in (" . $temas . ")";
but your case, . comes first that makes life so much harder, so a better solution would be
$temas1 = explode( '.', $_POST['temas'] );
$temas2 = array();
foreach( $temas1 as $value ) {
if( is_numeric( $value )) $temas2[] = $value;
}
$query = "select * from tb_preguntas WHERE tema in (" . implode( ',' , $temas2 ) . ")";
Use explode() to split those numbers by .And it must turn into array.
Then run your queries into a loop using the lenth of the array like this:
$id = explode('.',$temas);
foreach($id as $temas_id) {
$query = "SELECT * FROM tb_preguntas WHERE tema = '".$temas_id."'";
if(isset($conn->query(query ))) {
// Execute code here if there's a result.
}
}
Please try this code.
$temas = $_POST['temas'];
$temas = explode('.',$temas);
$query = mysql_query("SELECT * FROM test_stipe WHERE tema in '".implode("', '", $temas)."'");
This code is working fine.
I'm getting error "Undeclared variable: $start" while using the SQL query below.
<?php
if($Spage == ""){
$Spage = "1";
}
$Sper_page = "5";
$start = ($Spage-1)*$Sper_page;
$sResults = $oCon->dbFetchSmarty("SELECT * FROM experts WHERE exp_process LIKE '%".$process."%' AND exp_machinaries like '%".$machineCat."%' AND exp_country = '". $country."' 'LIMIT $start, $Sper_page'");
?>
You have messed your single quotes. Should be
$sResults = $oCon->dbFetchSmarty("SELECT * FROM experts WHERE exp_process LIKE '%".$process."%' AND exp_machinaries like '%".$machineCat."%' AND exp_country = '". $country."' LIMIT $start, $Sper_page");
And cleaning up the query a bit:
$sResults = $oCon->dbFetchSmarty("SELECT * FROM experts WHERE exp_process LIKE '%$process%' AND exp_machinaries like '%$machineCat%' AND exp_country = '$country' LIMIT $start, $Sper_page");
Next step to remove would be to use prepared statements and bind these parameters in
Try this: (another way in setting Limit and Offset)
<?php
if($Spage == ""){
$Spage = "1";
}
$Sper_page = "5";
$start = ($Spage-1)*$Sper_page;
$sResults = $oCon->dbFetchSmarty("SELECT * FROM experts WHERE exp_process LIKE '%".$process."%' AND exp_machinaries like '%".$machineCat."%' AND exp_country = '". $country."'LIMIT $per_page OFFSET $start'");
?>
And BTW you misplaced a single quote near LIMIT.
You are making the creation of your query much too complicated and therefore missing some simple errors. Remember that when you use double quoutes " in PHP it will expand $variables into the string for you.
So a simpler and easier to read and therefore debug method would be this
$sql = "SELECT * FROM experts
WHERE exp_process LIKE '%$process%'
AND exp_machinaries like '%$machineCat%'
AND exp_country = '$country'
LIMIT $start, $Sper_page";
$sResults = $oCon->dbFetchSmarty($sql);
You left out a space between LIMIT and '.
It must've been
$country."' ' LIMIT . ........
For best solution to check query is in phpmyadmin. You just echo query and copy/past query section into phpmyadmin. so it will give a proper guidance for your structure of query or any error for same.
CODE :
$nerd_result = mysql_query("select * from nerd_profile where nerd_reg_no = '$reg_no'");
$nerd_data = mysql_fetch_array($nerd_result);
$tags = array();
$tags = explode(",",$nerd_data['nerd_interests']);
for($i = 0; $i < sizeof($tags)-1; $i++)
{
if($i != sizeof($tags)-2)
{
$sub_query = $sub_query."`tags` like %".$tags[$i]."% or ";
}
else
{
$sub_query = $sub_query."`tags` like %".$tags[$i]."% ";
}
}
$proper_query = "select * from `qas_posts` where ".$sub_query." and `post_date` like '%$today%'";
$result = mysql_query($proper_query);
while($each_qas = mysql_fetch_array($result))
Description :
I am adding the like clause along with php variable in a string and concatenating it with the further variables with like clause to come. In the end when I echo I get the perfect query that I want but
mysql_fetch_array()
does not accept that generated query rather if I hard code it , it works perfect what am I doing wrong ?? can I do that ??
When doing string comparisons in mysql you need to make sure you have quotes around your comparison value.
$sub_query = $sub_query."`tags` like '%".$tags[$i]."%' or ";
and
$sub_query = $sub_query."`tags` like '%".$tags[$i]."%' ";
My code checks if there is $GET value, if not then assign ALL values of array.
Seems like simple thing,not sure why its not working.
if(isset($_GET["smonth"])) {$smonth= $_GET["smonth"];
}
else {$smonth =12;} working , but not what I want
else {$smonth =array (1,2,3,4,5,6,7,8,9,10,11) ;}
After that I would like to use it in SQL :
and d.month_of_year = '".$smonth."%'
That would be something like
and month_of_year = (all values of array) or 1 value)
My Question:
What would be best solution to check, if active month is available? If not, assign All months to query.Thank You
The built-in PHP functions of in_array and implode should solve your issue:
in_array('1', $_GET["smonth"]); // checks if January is in $_GET["smonth"]
implode("," , $_GET["smonth"]); // Pull all of the values out of $_GET["smonth"] as a A STRING
Try in your statement and d.month_of_year IN (" . implode(',', $smonth) . ")
= operator checks for single value. If you want to check multiple values, use in.
and d.month_of_year in (".$smonth.")
You also have a % there, which works with LIKE queries.
<?php
if(isset($_GET['month'])){
$month = date('m'); //This would give you the index of the current month.
$array = array('01','02','02');
$query = "select * from table where month = ";
if(in_array($month,$array)){
$query = "select * from table where month = '".$month."'";
//Then query here
}
else
{
$query = "select * from table";
$where = "";
foreach($month as $m){
$where .= ' month = "'.$m.'" and ';
}
//There would be a ending and pls just try remove it
$query .= $where;
// then query here
}
}
?>
i'm using this mysql query alongwith php to search for multiple keywords:
$query = "SELECT cQuotes, vAuthor, cArabic, vReference FROM ".$table." WHERE (";
$countFields = count($arrayFields);
while ($a < $countFields)
{
while ($b < $countSearch)
{
$query = $query."$arrayFields[$a] LIKE '%$arraySearch[$b]%'";
$b++;
if ($b < $countSearch)
{
$query = $query." AND ";
}
}
$b = 0;
$a++;
if ($a < $countFields)
{
$query = $query.") OR (";
}
}
$query = $query.")";
$result = mysql_query($query, $conn)
i'd like to reuse this query with a few modifications to it (for instance, the WHERE clause remains the same, while i query the number of rows using COUNT), but it doesn't seem practical to repeat the code again for a few additions. any suggestions?
I don't understand exactly what you're doing since there's code missing, but I'd suggest the following:
Don't use while with arrays; use foreach it's much more compact and that's what it was made for.
Don't concatenate strings manually, use implode()
Don't add complexity to your SQL to count result; use MYSQL's FOUND_ROWS() instead.
On a somewhat unrelated note I'd suggest upgrading from PHP's mysql library to mysqli. It allows multiple queries, which will make your life easier.
You could pull that code out into a separate function, then send it a parameter telling the function what version of the query you want. The function would then construct the query and return the string. I also think prepared statements might be beneficial to you.
You could try using a query builder library or ORM, especially if this problem is happening repeatedly. They allow you to create SQL functionally. I would suggest using Doctrine or Sqloo (spoiler alert: I'm the creator of Sqloo). Since you can use them to functionally create SQL, you can even pass partial queries around since they object, to allow for a very high reuse of code.
A few examples for Doctrine and Sqloo.
<?php
$table = "myTable";
$justCount = true;
$requiredFields = array('cQuotes', 'vAuthor', 'cArabic', 'vReference');
$arrayFields = array('cQuotes','vAuthor');
$arraySearch = array('blah','foo','bar');
///////////////
$selectWhat = $justCount ? "COUNT(*)" : implode(',', $requiredFields);
$wherePart = array();
foreach($arraySearch as $search)
{
$subWherePart = array();
foreach($arrayFields as $field)
{
$subWherePart[] = $field . " LIKE '%" . $search ."%'";
}
$wherePart[] = "(" . implode(" AND ", $subWherePart) . ")";
}
$query = "SELECT " . $selectWhat . " FROM " . $table
. " WHERE " . implode(" OR ", $wherePart);
?>
don't forget to filter input search words to avoid SQL Injection.