This is sql table
id id_user id_userfor description date
1 231 119 a to b 2010-02-05 17:42:47
2 231 231 myself 2010-02-05 17:36:28
3 231 119 from x to b 2010-02-05 17:36:29
I could not find the way to select output result which looks something like this:
user 119
a to b 2010-02-05 17:42:47
from x to b 2010-02-05 17:36:29
user 231
myself 2010-02-05 17:36:28
You can use
select id_userfor, description, date from table order by id_userfor;
then you can print all the date column data for each distinct id_userfor
$old = '';
while($row = mysql_fetch_array($result)) {
if($old != $row['id_userfor']) {
$old = $row['id_userfor'];
echo "$row['id_userfor']<br />";
}
echo $row['description'] . " " . $row['date'] . "<br />";
}
You can query with the id_userfor field sorted Then loop all record and everytime you encounter a new value of id_userfor print it.
Something like this:
$SQL = 'select * from ... order by `id_userfor`';
$Result = ...;
$PrevUserFor = '';
while($Row = ...) {
const $UserFor = $Row['id_userfor'];
if ($PrevUserFor != $UserFor) {
// Here is where you print the user ID
echo "user $UserFor<br>";
$PrevUserFor != $UserFor;
}
$Description = $Row['description'];
$Date = $Row['date'];
echo(' $Description $Date<br>');
}
Hope this helps.
The codaddict query a little more readable:
SELECT `id_userfor`, `description`, `date` FROM `table` ORDER BY `id_userfor`
And then, inside the loop, you'll use something like this:
$sql = "SELECT `id_userfor`, `description`, `date` FROM `table` ORDER BY `id_userfor`";
$query = mysql_query($sql);
$user = null; // Empty user
while($data = mysql_fetch_assoc($query)) {
if ($data['id_userfor'] != $user) {
// Display the user only when it changes
echo '<H1>'. $data['id_userfor'] .'</H1>';
$user = $data['id_userfor'];
}
// Display the rest of the fields here :)
}
Related
I have a query:
$string = "SELECT COUNT(id) as sponsered FROM `$database`.`$mem` where parent_id = 2 group by plan";
Which result in:
sponsored plan
2 gold
1 silver
1 mitra
This result is shown when I run this query in MySQL.
Now I want this result in PHP in an array data[] where
data[0] contains 2
data[1] contains 1
data[2] contains 1
I have tried this
$string = "SELECT COUNT(id) as sponsered FROM $database.$mem where parent_id = 2 group by plan";
$res = mysqli_query($con, $string);
while($data = mysqli_fetch_assoc($res)) {
echo $data['sponsered'];
}
But it results in data['sponsered'] containing 211
It would be better if this can be done without using any loop.
Inside the while loop assign the values to array.
$string = "SELECT COUNT(id) as sponsered FROM $database.$mem where parent_id = 2 group by plan";
$res = mysqli_query($con, $string);
$data = array();
while($result = mysqli_fetch_assoc($res)) {
$data[] = $result['sponsered'];
}
print_r($data);
Output:
data[0] contains 2
data[1] contains 1
data[2] contains 1
Your display is correct you just need a separator so the data isn't all clumped. In a browser:
echo $data['sponsered'] . "<br>";
in your loop should do it, or command line,
echo $data['sponsered'] . PHP_EOL;
should do it.
As is it throws 2, then 1, then 1 which views as 211.
Try this:
Please refrain from passing data directly into query in a prepare statement, use ? or : as deemed necessary.
Below is a sample code:
<?php
$table_name = $table; //not recommended to pass table_name as variable, unless necessary.
$parent_id = 2;
$p = $plan;
$string = "SELECT COUNT(id) as sponsered FROM $table_name where parent_id = ? group by ?";
if ($stmt = $db->prepare($string))
{
$stmt->bind_param('is', $parent_id, $p);
$stmt->execute();
$stmt->bind_result($sponsored, $plan);
$stnt->store_result();
$html ='';
while ($stmt->fetch() !== FALSE)
{
// Do what you like with the variables here, i.e. $sponsored, $plan
$html .= "<table>
<th> Sponsored </th>
<th> Plan</th>
<tr>
<td>$sponsored</td>
<td>$plan</td>
</tr>
</table>";
}
else {
die("Query failed");
}
var_dump($html);
}
?>
NOTE: If your result from your question is just an HTML (table/column), you don't need to do bind, you can just output the HTML formatted.
Use mysqli_fetch_array($result, MYSQLI_NUM) to retreive the data as numeric array
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 a problem realizing some output to echo a list of results that comes from an Array.
I would like to create a Live search engine that runs a query by the help of keyup-function by using AJAX.
Everything works fine when the output will be echoed for every match that is listed in the table.
Now I would like to to combine all entries that are duplicates.
The code is like:
$search_term = $_POST['search_term'];
$where = "";
$search_term = preg_split('/[\s]+/', $search_term, -1, PREG_SPLIT_NO_EMPTY);
$total_search_terms = count($search_term);
$total_search_term = 0;
foreach ($search_term as $key=>$value) {
$total_search_term = $total_search_term + 1;
if ($total_search_term === 1){
if (is_numeric($value) ){
$where .= "(`a` LIKE '%$value%')";
} else {
$where .= "(`b` LIKE '%$value%')";
}
}else if ($total_search_term > 1){
$where .= " AND ";
if (is_numeric($value) ){
$where .= "(`a` LIKE '%$value%')";
} else {
$where .= "(`b` LIKE '%$value%')";
}
}
}
$duplicate = $db->query("SELECT a, b, COUNT(*) counter
FROM `table`
GROUP BY a, b
HAVING COUNT(*) > 1
");
$check = $duplicate->fetch_assoc();
$query = $db->query("SELECT a, b FROM table WHERE $where");
$result = $query->num_rows;
if ($result !== 0 ){
echo '<li id="hit">There are $result results!</li>';
while ($row = $query->fetch_assoc() ) {
echo '<li>',
$row["a"],
' ',
$row["b"],
'</li>';
}
} else {
echo '<li id="hit">no result!</li>';
}
To give an example of the output:
There are 3 results!
12345 New
12345 New
56789 Chicago
And thats how it should be:
There are 3 results!
12345 New (2x)
56789 Chicago
So the table is:
a | b
12345 New
12345 New
56789 Chicago
Thanks alot.
I thought of something like this:
$query = $db->query("SELECT a, b, COUNT(*) counter FROM `table` WHERE ".$where." GROUP BY a, b");
$result = $query->num_rows;
if ($result !== 0 ){
$resultSizeQuery = $db->query("SELECT COUNT(*) counter FROM `table` WHERE ".$where);
$resultSize = $resultSizeQuery->fetch_assoc();
echo '<li id="hit">There are '.$resultSize["counter"].' results!</li>';
while ($row = $query->fetch_assoc() ) {
echo '<li>'.$row["a"].' '.$row["b"];
echo ($row["counter"] > 1 ? " (".$row["counter"]."x)" : "");
echo '</li>';
}
} else {
echo '<li id="hit">no result!</li>';
}
Replacing all lines from "$duplicates = ..." to the end it should do it's work. Just give it a try because sometimes the step before the problem should be thought over.
Regards
parascus
first of all, your statement will return just 1 line with New York and the column counter will have 2. Chicago is missing because counter is just 1.
So I think your result looks like:
Ther are 1 results!
12345 New York
If you want to have "3 results" jsut do 2 queries, one for the number of rows (just leave out the group and having clause, also don't ask for a and b).
So you get the output:
There are 3 results!
Next you have to omit the having clause for getting all rows (also those without duplicates). You could write something like:
echo ($row["a"].' '.$row["b"].($row["counter"] > 1 ? " (".$row["counter"]."x)" : "")
I hope this helps.
Regards
Parascus
I was wondering if there was an easy way to do this:
I have a user_id column and then 33 other columns with either a '0' or a '1' as the type. How can I easily select all of the columns where the user_id = 320 and the column's data equals 1?
The column titles are labeled 1-33. In the end I want to join it to another table where 1-33 is the id to a label column.
Does this make sense?
Thanks for any help!
Try this I get all the fields and test if it BIT and then inject it to the query
And please tell me the result
<?php
$result = mysql_query("SHOW COLUMNS FROM sometable");
if (!$result){
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0){
$str ="";
$nums = mysql_num_rows($result);
$i = 0 ;
while ($row = mysql_fetch_assoc($result)){
$i++;
if($row['Type'] = 'BIT' && $i != $nums){
$str .= " WHERE `".$row['Field']."` = 1 AND";
}
elseif($row['Type'] = 'BIT' && $i == $nums){
$str .= " WHERE `".$row['Field']."` = 1 ";
}
}
}
$query = "SELECT * FROM mytable user_id = 320 AND ".$str;
$q = mysql_query($query);
This is for the first part of you question
the second part the same operation
and this working without knowing the fields name
I have a table with 12 columns and 200 rows. I want to efficiently check for fields that are empty/null in this table using php/mysql. eg. "(col 3 row 30) is empty". Is there a function that can do that?
In brief: SELECT * FROM TABLE_PRODUCTS WHERE ANY COLUMN HAS EMPTY FIELDS.
empty != null
select * from table_products where column is null or column='';
SELECT * FROM table WHERE COLUMN IS NULL
As far as I know there's no function to check every column in MySQL, I guess you'll have to loop through the columns something like this...
$columns = array('column1','column2','column3');
foreach($columns as $column){
$where .= "$column = '' AND ";
}
$where = substr($where, 0, -4);
$result = mysql_query("SELECT * FROM table WHERE $where",$database_connection);
//do something with $result;
The = '' will get the empty fields for you.
you could always try this approach:
//do connection stuff beforehand
$tableName = "foo";
$q1 = <<<SQL
SELECT
CONCAT(
"SELECT * FROM $tableName WHERE" ,
GROUP_CONCAT(
'(' ,
'`' ,
column_name,
'`' ,
' is NULL OR ',
'`' ,
column_name ,
'`',
' = ""' , ')'
SEPARATOR ' OR ')
) AS foo
FROM
information_schema.columns
WHERE
table_name = "$tableName"
SQL;
$rows = mysql_query($q1);
if ($rows)
{
$row = mysql_fetch_array($rows);
$q2 = $row[0];
}
$null_blank_rows = mysql_query($q2);
// process the null / blank rows..
<?php
set_time_limit(1000);
$schematable = "schema.table";
$desc = mysql_query('describe '.$schematable) or die(mysql_error());
while ($row = mysql_fetch_array($desc)){
$field = $row['Field'];
$result = mysql_query('select * from '.$schematable.' where `'.$field.'` is not null or `'.$field.'` != ""');
if (mysql_num_rows($result) == 0){
echo $field.' has no data <br/>';
}
}
?>
$sql = "SELECT * FROM TABLE_PRODUCTS";
$res = mysql_query($sql);
$emptyFields = array();
while ($row = mysql_fetch_array($res)) {
foreach($row as $key => $field) {
if(empty($field)) || is_null($field) {
$emptyFields[] = sprintf('Field "%s" on entry "%d" is empty/null', $key, $row['table_primary_key']);
}
}
}
print_r($emptyFields);
Not tested so it might have typos but that's the main idea.
That's if you want to know exactly which column is empty or NULL.
Also it's not a very effective way to do it on a very big table, but should be fast with a 200 row long table. Perhaps there are neater solutions for handling your empty/null fields in your application that don't involve having to explicitly detect them like that but that depends on what you want to do :)
Check this code for empty field
$sql = "SELECT * FROM tablename WHERE condition";
$res = mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
foreach($row as $key => $field) {
echo "<br>";
if(empty($row[$key])){
echo $key." : empty field :"."<br>";
}else{
echo $key." =" . $field."<br>"; 1
}
}
}
Here i'm using a table with name words
$show_lang = $db_conx -> query("SHOW COLUMNS FROM words");
while ($col = $show_lang -> fetch_assoc()) {
$field = $col['Field'];
$sel_lan = $db_conx -> query("SELECT * FROM words WHERE $field = '' ");
$word_count = mysqli_num_rows($sel_lan);
echo "the field ".$field." is empty at:";
if ($word_count != 0) {
while($fetch = $sel_lan -> fetch_array()){
echo "<br>id = ".$fetch['id']; //hope you have the field id...
}
}
}
There is no function like that but if other languages are allowed, you can extract the structure of a table and use that to generate the query.
If you only need this for a single table with 30 columns, it would be faster to write the query by hand...