I have a MySQL table with multiple columns, from which I need to select all of them of each record, and to create a specific $key=>$value from it.
for example
TABLE
ID | group_cat | group_sec | group_name | enabled | sent
-------------------------------------------------------------------------------------
1 | C | sct_a | Project_A | 1 | no
2 | C | sct_b | Project_B | 1 | no
3 | P | sct_c | Moderators | 1 | no
4 | C | sct_d | Ambassad | 1 | no
5 | P | sct_e | PMP | 0 | no
The MySQL query I need is "SELECT * FROM groups WHERE sent = 'no' "
By PHP is
PHP Code
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $key => $value) { $$key = $value; }
...
...
...
}
Here my question:
I need that the $key is from the column 'group_sec' and the related $value is from the column 'group_name'. So that the couple $$key=>$value can return this result (for instance)
echo $sec_b;
returns: Project_B
Could you help me to get this done please?
Thank you in advance
This will do the job for you:
${$row['group_sec']} = $row['group_name'];
echo $sct_b;
Output:
Project_B
You would use this in your while loop (the foreach can probably be deleted):
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
${$row['group_sec']} = $row['group_name'];
...
// do something with $sct_b
...
}
Alternatively, if your column names might change, but the positions will stay the same, you can use
while($row = $sth->fetch(PDO::FETCH_NUM)) {
${$row[2]} = $row[3];
...
// do something with $sct_b
...
}
You can build an array based on key and value you prefer using $row['group_sec'] for key and $row['group_name'] eg:
$query = "SELECT * FROM `groups` WHERE `sent`= 'no' ";
$sth = $sql->prepare($query);
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$myArray[$row['group_sec']] = $row['group_name'];
}
and you can see the result
foreach($myArray as $key => $value){
echo $key . ' - ' . $value . '<br>';
}
$sql = "SELECT * FROM groups WHERE sent= 'no'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$list=[];
while($row = $result->fetch_assoc()) {
$list{$row['group_sec']} = $row['group_name'];
}
}
I want to find a value from a column which has multiple values like (23,24,25), Using php mysqli query.
Table:
+-----------------+
id | tag_ids |
+-----------------+
1 | 3,4,5 |
2 | 3,7,8,9 |
3 | 4,5,10 |
Curent query:
$value = '3';
$query = "SELECT tag_ids FROM table WHERE FIND_IN_SET($value, tag_ids)";
$result = mysqli_query($query);
$count = mysqli_num_rows($result);
echo count;
Result will be: YES/NO or 1/0, if the Given value is match any value with tag_ids.
I found the result my self and here is code:
function statusvalues() {
$query = "SELECT tag_ids FROM tblname WHERE tag_ids !=''";
$result = mysqli_query($query, DBCONN);
$idarray = array();
while($row = mysqli_fetch_array($result)) {
array_push($idarray, $row['tag_ids']);
}
return $idarray;
}
function status($ID) { //Passing tag id
$set_of_numbers = statusvalues();
$reset_numbers = implode(", ", $set_of_numbers);
$values = explode(", ", $reset_numbers);
if (in_array($ID, $values)){
return "disabled";
}
}
I have a while loop that is supposed to first get the individual_id from a table called submittedresume using the job_id that it gets from another function. It would then use that id in another while loop to get the first_name and last_name from the individual table. It would then use another while loop to get the submitted_id from the submitted resume table.
I split the first and last while loop to get distinct values from the output.
My first while loop. It first gets the individual_id from a table called submittedresume using the job_id that it gets from another function. It gives me the correct output of two user ids: 9 and 4.
global $database;
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
while ($row = mysqli_fetch_array($output)) {
$indvId = $row[0];
}
This is the second inner while loop. It gives me an output of Mary Jane (No repeat) and Tom Sawyer.
$indvId = $row[0];
$sql = "SELECT * FROM individual WHERE individual_id='$indvId'";
$result = $database->query($sql);
while ($details = mysqli_fetch_array($result)) {
$first = $details['first_name'];
$last = $details['last_name'];
echo $first;
echo $last;
}
This is my whole function:
public function displayApplications($id){
global $database;
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
while ($row = mysqli_fetch_array($output)) {
$indvId = $row[0];
$sql = "SELECT * FROM individual WHERE individual_id='$indvId'";
$result = $database->query($sql);
while ($details = mysqli_fetch_array($result)) {
$first = $details['first_name'];
$last = $details['last_name'];
$sqlquery = "SELECT DISTINCT resume_title FROM submittedresume WHERE individual_id='$indvId' order by submitted_id";
$data = $database->query($sqlquery);
if (mysqli_num_rows($data) == 0) {
echo "Database is empty <br>";
} else {
while (($name = mysqli_fetch_array($data))) {
echo $first . " " . $last . " "."<a href=handleDownload.php?id=$id>$name[0]</a><br>";
}
}
}
}
}
This is what I'm getting right now:
first_name | last_name | resume_name
Mary | Jane | resume_1
Mary | Jane | resume_2
This is what I'm looking for:
first_name | last_name | resume_name
Mary | Jane | resume_2
Tom | Sawyer | resume_1
I think after while use foreach loop:
For example:
$query = "SELECT DISTINCT individual_id FROM submittedresume WHERE job_post_id='$id'";
$output = $database->query($query);
$details = mysqli_fetch_array($result);
foreach($details as $key => $value){
echo 'Key: '. $key . ' '. 'Value: '. $value;
}
$indvId = $row[0]; is returning the 1st item in the result array
I personally would use a foreach loop but you could do it the way you have it by adding a counter ie: $count = 0; before the loop and $count++; inside the loop and $indvId = $row[$i];
i have such a table:
r_id date recipe_name
1 2012-05-20 Cheese Bread
1 2012-05-21 Cheese pie
2 2012-05-20 Spanish Bread
I would like to get all the data under r_id 1 to be in a single row how can i do that using Sql.I need to achieve something like this:
r_id recipe_name
1 Cheese Bread,Cheese pie
2 Spanish Bread
how can i do this using php too?
Use GROUP_CONCAT
SELECT r_id, GROUP_CONCAT(recipe_name)
FROM yourTable
GROUP BY r_id
Here's the php version
$query = "SELECT id, recipe_name FROM myTable";
$rs = mysqli_query($query);
$results = array();
while($r = mysqli_fetch_assoc($rs)) {
$results[$r['id']][] = $r['recipe_name'];
//$results[$r['id']][] = "<a href=''>".$r['recipe_name']."</a>";
}
foreach($results as $id => $recipes) {
print $id . ' ' . implode(',', $recipes) . "<br>";
}
I have a string containing comma separated keywords. For Example:
$keywords = 'keyword1, keyword2, keyword3';
My Table schema, named tbl_address is like this ( simplified ) :
id INT(11) PRIMARY KEY, AUTO INCREMENT
address VARCHAR(250) NOT NULL
Assume I have to use MySQLi in PHP ( not PDO ).
Here is my current approach:
$result = array();
$keyword_tokens = explode(',', $keywords);
foreach($keyword_tokens as $keyword) {
$keyword = mysqli_real_escape_string(trim($keyword));
$sql = "SELECT * FROM tbl_address WHERE address LIKE'%$keyword%'";
// query and collect the result to $result
// before inserting to $result, check if the id exists in $result.
// if yes, skip.
}
return $result;
This approach works, but inefficient in performance. If there are a lot of keywords, it will make a lot queries.
My question is, is there a better way to achieve the same goal ? i.e. what is the simplest way to return all records with the address containing the ANY of the keywords ?
A simple REGEXP might be what you're after. You'd have to check how efficient it is for yourself.
SELECT * FROM tbl_address WHERE field REGEXP 'keyword1|keyword2|keyword3';
SELECT * FROM user;
+---------+----------+
| user_id | username |
+---------+----------+
| 101 | Adam |
| 102 | Ben |
| 103 | Charlie |
| 104 | Dave |
+---------+----------+
SELECT *
FROM user
WHERE FIND_IN_SET(username,'adam,ben,dave') > 0;
+---------+----------+
| user_id | username |
+---------+----------+
| 101 | Adam |
| 102 | Ben |
| 104 | Dave |
+---------+----------+
You only need an 'OR', nothing else...
<?php
$result = array();
$keyword_tokens = explode(',', $keywords);
$keyword_tokens = array_map('mysqli_real_escape_string', $keyword_tokens);
$sql = "SELECT * FROM tbl_address WHERE address LIKE'%";
$sql .= implode("%' or address LIKE '%", $keyword_tokens) . "'";
// query and collect the result to $result
// before inserting to $result, check if the id exists in $result.
// if yes, skip.
return $result;
edit: Just to be sure you also trim the keywords
<?php
$result = array();
$keyword_tokens = explode(',', $keywords);
$keyword_tokens = array_map(
function($keyword) {
return mysqli_real_escape_string(trim($keyword));
},
$keyword_tokens
);
$sql = "SELECT * FROM tbl_address WHERE address LIKE'%";
$sql .= implode("%' OR address LIKE '%", $keyword_tokens) . "'";
// query and collect the result to $result
// before inserting to $result, check if the id exists in $result.
// if yes, skip.
return $result;
Also, you should also pass the db resource link to the mysqli_real_escape_string() function...
The best way is to use fulltext search.
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
if you don't want to use fulltext you can use OR in your WHERE condition
SELECT * FROM tbl_address WHERE address LIKE '%$keyword%' OR adress LIKE '%$keyword2%'
Try WHERE IN clause:
$keyword = (array)explode(',', $keywords);
for($i=0;$i=count($keyword);$i++){
$keyword[$i]=mysqli_real_escape_string(trim($keyword[$i]),'\'" ');
}
//This is what I suggest.
$query='SELECT * FROM tbl_address WHERE address IN ("'.implode('","',$keyword).'")';
Successfully tested on MySQL 5.1.
Make single query
$keywordary = explode(',', $keywords);
foreach($keywordary as $keyword) {
$keys = trim($keyword);
$other .=" or address like '%$keys%'";
}
$sql = "SELECT * FROM tbl_address WHERE address LIKE'%$keyword%' $other";
execute query;
return $result;
Best way is just create search string WHERE clause and append it to query and run it once.
$result = array();
$keyword_tokens = explode(',', $keywords);
$where = '';$i=0
foreach($keyword_tokens as $keyword) {
$where.= " address LIKE'%".mysqli_real_escape_string(trim($keyword))."%' OR ";
}
// trim last OR with substr_replace
substr_replace($where, "OR", -1, 1);
$sql = "SELECT * FROM tbl_address WHERE $where";
return $result;
Hi create a query with union and execute in the end of the loop
$result = array();
$keyword_tokens = explode(',', $keywords);
$sql = '';
foreach($keyword_tokens as $keyword) {
$keyword = mysqli_real_escape_string(trim($keyword));
if (!empty($sql)) $sql .= " UNION ";
$sql .= "SELECT * FROM tbl_address WHERE address LIKE'%$keyword%'";
// query and collect the result to $result
// before inserting to $result, check if the id exists in $result.
// if yes, skip.
}
Execute the query here.