php Mysql query in a while loop - php

I'm new to php and i don't have the formal study, since i study it myself
i have a problem and i hope someone can help me.. :(
I have and array
$array = array("where","are","you" and so on.....);
and i want to search the database with all those values
like
$sql_res1 =mysql_query("select * from lady_vega where react like '%$array[0]%'");
$sql_res2 =mysql_query("select * from lady_vega where react like '%$array[1]%'");
$sql_res3 =mysql_query("select * from lady_vega where react like '%$array[2]%'");
.... and so on
there are times that the array don't have the exact number of values.
and someone said to me that loop could be a help...
but i don't know how...
and i also want the results of each mysql query will be stored like this so that i can i dentify which results are from...
$row1 = mysql_fetch_array($sql_res1);
$row2 = mysql_fetch_array($sql_res2);
$row3 = mysql_fetch_array($sql_res3);
... so on
i hope there would a possible solution/technique to this..

Try using the following:
$sql = "select * from lady_vega where react like '%".implode("%' OR react LIKE '%", $array)."%'"
$sql_res1 =mysql_query($sql);
You can chain multiple where clauses using OR and AND in your query:
WHERE field = 'value' AND field2 = 'value'

You could try using a foreach loop for example.
$terms = explode(",",$array);
$query = "select * from lady_vega where ";
foreach($terms as $each){
$i++;
if($i ==1){
$query.="react LIKE '%$each%'";
}
else
$query .= "OR react LIKE '%$each%' ";
}

$sql = "";
for($i=0;$i<count($array);$i++){
$sql.="select *,'".$array[$i]."' as keyword from lady_vega where react like '%".$array[$i]."%'";
if($i!=count($array)-1) $sql .= " union ";
}
$result = mysql_fetch_array(mysql_query($sql));
$last_keyword="";
$index = 1;
foreach($result as $row){
if($last_keyword!=$row["keyword"]){
$index++;
${"row".$index} = array();
}
array_push(${"row".$index},$row);
}
then you'll get the same result with an extra "keyword" column.

Related

Dynamic value in sql query using php

I want to search a certain string in all the columns of different tables, so I am looping the query through every column name. but if i give it as dynamic value it does not seem to work.
what is wrong?
<?php
$search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'feedback'";
$columns_result = $conn->query($columns);
$columns_array = array();
if (!$columns_result) {
echo $conn->error;
} else {
while ($row = $columns_result->fetch_assoc()) {
//var_dump($row);
//echo $row['COLUMN_NAME']."</br>";
array_push($columns_array, $row['COLUMN_NAME']);
}
}
var_dump($columns_array);
$row_result = array();
for ($i = 0; $i < count($columns_array); $i++) {
echo $columns_array[$i] . "</br>";
$name = "name";
// $sql = 'SELECT * FROM feedback WHERE "'.$search.'" in ("'.$columns_array[$i].'")';
$sql = 'SELECT * FROM feedback WHERE ' . $name . ' like "' . $search . '"';
$result = $conn->query($sql);
if (!$result) {
echo "hi";
echo $conn->error;
} else {
foreach ($result as $row) {
array_push($row_result, $row);
echo "hey";
}
}
}
var_dump($row_result);
I am getting the column names of the table and looping through them because I have so many other tables which I need to search that given string. I don't know if it is optimal I did not have any other solution in my mind. If someone can tell a good way I will try that.
It looks to me that you want to generate a where clause that looks at any available nvarchar column of your table for a possible match. Maybe something like the following is helpful to you?
I wrote the following with SQL-Server in mind since at the beginning the question wasn't clearly tagged as MySql. However, it turns out that with a few minor changes the query work for MySql too (nvarchar needs to become varchar):
$search='%';$tbl='feedback';
if (isset($_POST['search'])) $search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = '$tbl' AND DATA_TYPE ='nvarchar'";
$columns_result = $conn->query($columns);
$columns_array = array();
if(!$columns_result) print_r($conn->errorInfo());
else while ($row = $columns_result->fetch(PDO::FETCH_ASSOC))
array_push($columns_array, "$row[COLUMN_NAME] LIKE ?");
$where = join("\n OR ",$columns_array);
$sth = $conn->prepare("SELECT * FROM $tbl WHERE $where");
for ($i=count($columns_array); $i;$i--) $sth->bindParam($i, $search);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
The above is a revised version using prepared statements. I have now tested this latest version using PHP 7.2.12 and SQL-Server. It turned out that I had to rewrite my parameter binding part. Matching so many columns is not a very elegant way of doing queries anyway. But it has been a nice exercise.
It looks like you are using mysqli, so I wanted to give another way of doing it via mysqli.
It does more or less the same as cars10m solution.
$search = $_POST['search'];
$columns = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'feedback'";
$columns_result = $conn->query($columns)->fetch_all(MYSQLI_ASSOC);
// Here dynamically prepare WHERE with all the columns joined with OR
$sql = 'SELECT * FROM feedback WHERE ';
$arrayOfWHERE = [];
foreach($columns_result as $col){
$arrayOfWHERE[] = '`'.$col['COLUMN_NAME'].'` LIKE ?';
}
$sql .= implode(' OR ', $arrayOfWHERE);
// prepare/bind/execute
$stmt = $conn->prepare($sql);
$stmt->bind_param(str_repeat("s", count($arrayOfWHERE)), ...array_fill(0, count($arrayOfWHERE), $search));
$stmt->execute();
$result = $stmt->get_result();
$row_result = $result->fetch_all(MYSQLI_ASSOC);
var_dump($row_result);
Of course this will search for this value in every column of the table. It doesn't consider data type. And as always I have to point out the using PDO is better than mysqli. If you can switch to PDO.

PHP mysql query issue when filtering from array and variables

On my webpage (html, php), I'm trying to get it such that users may select multiple checkboxes, each checkbox effectively filters what results the users see. Info is pulled from the database (MySQL) based on the values in different columns. As shown below, one column is Joint_1, another column is Position.
Effective code that WORKS for filtering (very static, not practical to use obviously) is this:
$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'region1\' OR
Joint_1=\'region2\' OR
Joint_1=\'region3\' OR
Joint_1=\'region4\') AND
(Position=\'position1\' OR
Position=\'position2\' OR
Position=\'position3\')";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["Common_Name1"] . "<br>";
}
} else {
echo "0 results";
}
Below code is attempts at above code, but using arrays, which does NOT work.
$regions =
array('region1', 'region2', 'region3', 'region4');
$position = array('position1', 'position2', 'position3');
$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'. $regions[0] .\' OR
Joint_1=\'. $regions[1] .\' OR
Joint_1=\'. $regions[2] .\' OR
Joint_1=\'. $regions[3] .\') AND
(Position=\'. $position[0] .\' OR
Position=\'. $position[0] .\' OR
Position=\'. $position[0] .\')";
Above code provides results of '0 results.'
I've attempted to perform this numerous times, with additional NON-FUNCTIONAL CODE also below (below attempting to filter based on only 1 column as I have obviously not mastered the code to approach filtering based on 2 columns).
$sqlregion = array();
foreach ($_POST['region'] as $reg) {
$sqlreg[] = "'" . mysql_real_escape_string($reg) . "'";
}
$sql = "SELECT * FROM 'Exercises' WHERE Joint_1 IN (" . implode(",",
$sqlreg) . ");";
$result=$conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["Common_Name1"] . "<br>";
}
}
Any help is appreciated! Thanks.
You can construct this query from arrays, you can use the IN clause in mysql to specify multiple OR values
$regions = array('region1', 'region2', 'region3', 'region4');
$position = array('position1', 'position2', 'position3');
$regions = implode(",", $regions); // Converts array to string with comma as a separator
$position = implode(",", $position);
$sql = "SELECT * FROM `Table_Name` WHERE Joint_1 IN ($regions) AND Position IN ($position)";
echo $sql;
This gives you a query like this
SELECT * FROM Table_Name WHERE Joint_1 IN (region1,region2,region3,region4) AND Position IN (position1,position2,position3)
add in your own LIMIT GROUP BY or ORDER BY parameters to suit your needs

PHP filter json using $GET in URL

I want my json be filtered with two rows using $GET in the url where I can type something like http://carkila.esy.es/carkila/user.php?owner=ownerANDstatus=pending can you please help me fix my code thanks. :)
<?PHP
include_once("connection.php");
session_start();
$where = '';
if (isset($_GET['owner']) && isset($_GET['status'])){
$where = " WHERE owner like '%".addslashes($_GET['owner'])."%' AND status like '%".addslashes($_GET['status'])."%'";
}
$query = "SELECT * FROM tbl_cars ".$where." ORDER BY Car_No DESC";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode($data);
?>
Use this: owner&status arguments seperator for a url.
You can also use
http_build_query (array('owner'=>'owner','status'=>'pending'))
to generate owner=owner&status=pending

PHP / Insert foreach in query

Im trying to fill query with array. As I know I can display array with function foreach(); but im not able to put it in mysql query
Im trying to do something like this:
<?php
$arr = array("arr_1", "arr_2", "arr_3", "arr_4");
$query = mysql_query("SELECT * FROM users WHERE user = '1'".
foreach($arr as $arr) {
echo "AND user = '".$arr++."'";
}
." ORDER BY id";
?>
Script have to display this as:$query = mysql_query("SELECT * FROM users WHERE user = '1' AND user = 'arr_1' AND user = 'arr_2' AND user = 'arr_3' AND user = 'arr_4'");
But this doesnt work becouse you cant put foreach() in mysql_query();.
So what I need is script that do the same thing ( display array in query string )
Thanks.
if you want to add multiple conditions from array, do concatenation instead of echo
<?php
$arr = array("arr_1", "arr_2", "arr_3", "arr_4");
$query = mysql_query("SELECT * FROM users WHERE user = '1'";
foreach($arr as $id) {
$query .= "AND user = '".$id."'";
}
$query .= " ORDER BY id";
?>
Not the best solution, but an alternative:
$arr = array("arr_1", "arr_2", "arr_3", "arr_4");
$arr_string="'".implode("','", $arr)."'"; // surround values in quotes
$query = mysql_query("SELECT * FROM users WHERE user IN (".$arr_string.") ORDER BY id";

MySQL with php variable trouble

I'm having trouble with putting a php variable into a mysql query.
For example:
mysql_query("SELECT * FROM listings WHERE title LIKE '%ipod%'");
That works, but
$key = "ipod";
mysql_query("SELECT * FROM listings WHERE title LIKE '%$key%'");
That doesn't work.
I might be doing it wrong though. If the above is the correct way to do it, then maybe another part of my script has a typo or something like that.
Any help would be great.
Your not selecting anything:
"SELECT * FROM listings WHERE title LIKE '%$key%'"
notice the *
Try this:
$key = "ipod";
mysql_query("SELECT * FROM listings WHERE title LIKE '%".$key."%'");
Try this:
$key = "ipod";
$results = mysql_query("SELECT * FROM listings WHERE title LIKE '$key'");
$num = mysql_num_rows($results);
echo "Received " . $num . "rows of results";
While ($row = mysql_fetch_assoc($results)) {
echo '<pre>';
print_r($row);
echo '</pre>';
}
$key = "ipod";
mysql_query("SELECT * FROM listings WHERE title LIKE '".$key."'");

Categories