I have a basic query as follows
$query = "SELECT * FROM files WHERE (subject_code = '".$subject_code."' )";
I have to modify this query to create a query where we have multiple subject codes fetched from an array.
$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
Now result holds all the required subject_codes say result[0]=SC1,result[1]=SC2 etc....
Now I want to the original query to be modified something as follows
$query = "SELECT * FROM files WHERE (subject_code = SC1 OR subject_code = SC2 .....)";
Note that i don't know what are the values of SC1 SC2 etc.It depends on the branch and is inside $result.
How can i accomplish this?
You can use a subquery like this:
$query = 'SELECT * FROM files
WHERE subject_code IN (
SELECT subject_code FROM subject WHERE sbranch = "' . $branch . '"
)';
You can use implode to convert array to string comma delimited
like below:
$branch_array = array('subject1', 'subject2', 'subject3');
$branch = implode("','", $subject_array );
$query1="SELECT subject_code FROM subject WHERE sbranch in ('".$branch."')";
result:
'subject1', 'subject2', 'subject3'
Hope that resolve your issue
You can use Mysql In operator
Like this
SELECT * FROM files WHERE subject_code in ('SC1','SC2')";
You can achieve ('SC1','SC2') by using implode php function,
like this:
$subCodes = implode("','", $subject_array );
SELECT * FROM files WHERE subject_code in ('".$subCodes ."')"
$query1="SELECT subject_code FROM subject WHERE (sbranch = '".$branch."' )";
$result = mysqli_query($bmysqli, $query1);
$codes=(array)$result; //this will convert it in normal array. old school typecasting ;)
$codes=array_values($codes);
$query = "SELECT * FROM files WHERE subject_code in (".implode(",",$codes).")";
//considering result is an object of subject codes.
CODE UPDATED ABOVE as it is an object.
You don't need to append to the first query. Just build a new query using MySQL in operator and php implode function.
SELECT * FROM files WHERE subject_code in ('SC1','SC2')
You can amend your php array to comma delimited string of SubjectCodes.
then:
$query1="SELECT * FROM files WHERE subject_code in (".$NewString.") ";
$NewString will look something like this:
"'SC1', 'SC2', 'SC3'"
$result = array(0=>'SC1',1=>'SC2'); //this is your array
$branch = implode("','", $result );
$query .= "
SELECT * FROM files WHERE subject_code in ('".$branch."') "; //this is query
Related
I have two tables is sql 1) friends_details and 2) user_info.
Now using the below query am getting the list of friends of that particular using $number = is coming from app
$sql = "select friends from user_info WHERE user_number ='$number' ";;
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
now $emparray have names of friends in String fromat. Now i want to pass this array into another query so that i can find the details of these friends. And Can't find the way to do. I have tried this code.
$friendsArray2 = "'" .implode("','", $emparray ) . "'";
$query120 = "SELECT * FROM friends_deataisl WHERE name IN ( $friendsArray2 )";
echo $query120;
and the result of echo $query120 is SELECT * FROM friends_deatails WHERE name IN ( 'Array','Array' )
So this means values are not going in the query. Any help would be appreciated.
And i have already checked $emparray is not empty it contains the name that means first query is right but the problem is in second query.
$emparray is a 2-dimensional array, not an array of strings, because $row in the first loop is an associative array.
You need to change the first loop to do:
$emparray[] = $row['friends'];
But you could just combine the two queries into a JOIN:
SELECT DISTINCT fd.*
FROM friend_details AS fd
JOIN user_info AS ui ON fd.name = ui.friends
WHERE ui.user_number = '$number'
Also, the column name friends makes me suspect that this is a comma-separated list of names. Using = or IN won't work with that -- it will try to match the entire list with friend_details.name. It's best to normalize your database so you don't have lists in a column. If you can't fix that, you need to use FIND_IN_SET to join the tables:
SELECT DISTINCT fd.*
FROM friend_details AS fd
JOIN user_info AS ui ON FIND_IN_SET(fd.name, ui.friends)
WHERE ui.user_number = '$number'
And in your original code, you'll need to explode $row['friends']:
$emparray = array_merge($emparray, explode(',', $row['friends']));
I'm working on a Wordpress plugin to search through all the users by first name, last name, email etc. It is working as long as I only use 1 of the values like first name.
I need to add all the values to the select!
I already tried adding more by using ',' and OR statements but it isn't working.
$results = $wpdb->prepare("SELECT * FROM users WHERE first_name LIKE %s", "%".$_POST['search']."%");
EDIT: found it
Found it!
$results = $wpdb->prepare("SELECT * FROM users WHERE lower(first_name) LIKE lower (%s) OR lower(last_name) LIKE lower(%s) LIKE lower(%s)OR lower(postcode) LIKE lower(%s)", "%".$_POST['search']."%", "%".$_POST['search']."%");
To get a literal % to pass through $wpdb->prepare just double it. You don't need to be avoiding $wpdb->prepare.
Proof of concept:
var_dump($wpdb->prepare('SELECT * FROM {$wpdb->posts} WHERE post_title LIKE "%%%s%%"','Hello'));
So your query should be :
$results = $wpdb->prepare("SELECT * FROM users WHERE first_name LIKE %%%s%%",$_POST['search']);
(more...)
Update
Use this for imploding OR :
$var[] = 'name LIKE "%%%s%%"';
$var_data[] = 'Hello';
$var[] = 'email LIKE "%%%s%%"';
$var_data[] = 'tt#tt.tt';
$var[] = 'date LIKE "%%%s%%"';
$var_data[] = 'Howdy';
var_dump($wpdb->prepare('SELECT * FROM users WHERE '.implode(' OR ',$var),$var_data));
Are you treating the object properly? This would iterate over the values retrieved
while($row = $results->fetch_assoc()){
echo $row['username'] . '<br />';
}
$results = mysql_query("select * from doctorlist where assignednumber = '1231231234' ");
I need to change the number 1231231234 to a variable. If I change it to the code below it does not work. I have displayed the variable on the page so I know it is set.
$results = mysql_query("select * from doctorlist where assignednumber = '$phoneNumber' ");
Could someone please help. I know it is a small issue, but have been unable to fix it.
Perhaps split it like this
$sql_query = "select * from doctorlist where assignednumber='$phoneNumber'";
$results = mysql_query($sql_query);
or
$sql_query = "select * from doctorlist where assignednumber='".$phoneNumber."' ";
$results = mysql_query($sql_query);
First check your variable type with var_dump($phoneNumber) than do the following:
$results = mysql_query("select * from doctorlist where assignednumber = '".$phoneNumber."' ");
to improve readability and last if you expect an Integer cast your variable like:
(int)$phoneNumber
or if string do
mysql_real_escape_string($phoneNumber)
Try using the variable inside the query like this:
'{$phoneNumber}'
I need to read a text file, query the database table with that name, and store that table's data in another table. So far I have written this code but I don't know why it's not working.
foreach ($lindb as $namedb) {
$query = "SELECT * FROM ntable WHERE name =" .$namedb. "";
$result = mysql_query($query);
while ($r = mysql_fetch_array($result)) {
$query = "INSERT INTO ndtable (name,details,address,login,country) VALUES (\"".$r["name"]."\", \"".$r["details"]."\", \"".$r["address"]."\", \"".$r["login"]."\", \"".$r["country"]."\")";
mysql_query($query);
}
}
You don't have quotes around $namedb
ie. SELECT * FROM ntable WHERE name =" .$namedb. ""; should be SELECT * FROM ntable WHERE name ='" .$namedb. "'";
I suggest a SELECT INTO would be the better choice... and please post the error so we are able to help...
If I have an array of say, some ID's of users. How could i do something like this:
$array = array(1,40,20,55,29,48);
$sql = "SELECT * FROM `myTable` WHERE `myField`='$array'";
Is there a simple way to do this, I thought about looping through array items and then building up one big "WHERE -- OR -- OR -- OR" statement but i thought that might be a bit slow for large arrays.
Use IN:
$sql = "SELECT * FROM `myTable` WHERE `myField` IN (1,40,20,55,29,48)";
you can use implode(",", $array) to get the list together from the array.
You want to use IN:
WHERE `myfield` IN (1,40,20,55,29,48)
Use implode to construct the string:
$sql = "SELECT * FROM `myTable` WHERE `myField` IN (" . implode(',', $array) . ")";