Mysql result to limit output - php

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

Related

Show query result in PHP

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

SQL query issues: [1] Count(*) and [2] using NOT vs <>

I have been staring at this code so long it is starting to bleed together. So let's get a couple things out of the way:
I am a low-moderate level SQL user and am still learning the best ways to accomplish queries and such
I have been building a PHP based quote-generator tool that ties in with an SQL database
Now, here is what I am trying to accomplish:
I would like to have pagination with the results of quotes that have been created with a status that is NOT "Dead", "Duplicate", or "Signed" and the ID does NOT equal 999 (because I wanted the quotes to jump to 1000 and I did not build the database correctly at first)
Here is what I have accomplished:
I was able to create the basic structure and it works just fine on page 1... then it all goes sideways. I was thinking that it was something to do with my count(*) query, but that seems fine - well functional, at least:
$countQry = "SELECT COUNT(*)
from needsassessment
WHERE ID <> 999
AND status <> 'Dead'
AND status <> 'Duplicate'
AND status <> 'Signed'";
$countResult = $mysqli->query($countQry);
while($rowQ = mysqli_fetch_array($countResult)) {
$totalRows = $rowQ[0];
$each = ceil($totalRows/$limit);
$where = "WHERE ID > 0";
if ($totalRows == 0) {
echo "You have not created any quotes.";
}
}
$limit = 15;
if (isset($_GET['q']) && $_GET['q'] !== "") {
$offset = $_GET['q'];
} else {
$offset = 0;
}
$query = "SELECT * FROM needsassessment $where
where $and
AND ID <> 999
AND NOT status = 'Dead'
AND NOT status = 'Duplicate'
AND NOT status = 'Signed'
ORDER BY ID DESC LIMIT $offset, $limit";
$result = $mysqli->query($query);
$row_cnt = mysqli_num_rows($result);
if ($row_cnt == 0) {
echo "You have not created any quotes."; die;
}
if (!isset($each)) {
$each = $row_cnt/$limit;
}
if ($each > 1) {
echo "<ul class='pagination'>";
for($i=1,$y=0;$i<=$each,$y<=($each-1);$i++,$y++) {
echo "<li><a";
if ($offset == ($y*15)) {echo ' class="active"';}
echo " href='?q=".($y*15)."'>$i</a></li>";
}
echo "</ul>";
}
Okay, so here are my questions:
I saw someone say that using PHP's mysqli_num_rows() is wrong and
that I should use SQL's COUNT(*). Why? Does it have a different result or take longer?
What is going on with page's
2 and 3? When I do a row count it says it sees 15 rows but only some
are showing. I have some records (i.e. those with a status of
"Signed" or "Dead") that are excluded from this list and I was
thinking that may have been the issue, but it doesn't seem to matter
on the first page.
What is the difference - if there is one -
between "NOT" and "<>" for checking records?
If you have any suggestions or if I have done anything blatantly wrong or inefficiently please let me know so I can correct it :)
Thanks to all that make Stack Overflow AWESOME!
EDIT:
There certainly was some code missing:
if (!isset($sst)) {
$where = "";
$sst = "";
$countQry = "SELECT COUNT(*) from needsassessment WHERE ID <> 999 AND status <> 'Dead' AND status <> 'Duplicate' AND status <> 'Signed'";
$countResult = $mysqli->query($countQry);
while($rowQ = mysqli_fetch_array($countResult)) {
$totalRows = $rowQ[0];
$each = ceil($totalRows/$limit);
$where = "WHERE ID > 0";
if ($totalRows == 0) {echo "You have not created any quotes.";}
}
}
else {
if ($option !== "*") {
$where = "WHERE ".$option." LIKE '%".$sst."%'";
}
if ($option == "*") {
$where = "WHERE status LIKE '%".$sst."%' OR title LIKE '%".$sst."%' OR propType LIKE '%".$sst."%' OR pSType LIKE '%".$sst."%' OR createDate LIKE '%".$sst."%'";
}
$offset = 0;
}
if ($_SESSION['admin'] >= 1) {
$and = "";
}
else {
$and = "AND creatorID = '".$_SESSION['user']."'";
}

How to pull columns with '1' in MySQL

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

Group PHP results on first letter of name

I have a query which gets all records ordered by last_name. Now I would like to create a loop that groups these results by the first letter of the last name and display the letter above the group i.e.
A
-----------
Albert
Alfred
C
-----------
Charles
D
-----------
Delta etc...
Thanks!
Order the results by lastname on MySQL side and track the change of the first letter on PHP side:
<?php
$rs = mysql_query("SELECT * FROM mytable ORDER BY lastname");
while ($rec = mysql_fetch_assoc($rs)) {
if ($initial !== strtoupper(substr($rec['lastname'], 0, 1)) {
$initial = strtoupper(substr($rec['lastname'], 0, 1));
print "$initial\n";
}
print $rec['lastname'] . "\n";
}
?>
$letter = null;
foreach ($array as $word) {
if ($letter != $word[0]) {
$letter = $word[0];
echo '<b>'.strtoupper($word[0]) . '</b><br/>';
}
echo strtoupper($word) . '<br/>';
}
and to tour query add line :
order by `your_field` asc
Allready tried something like this?
$last = '';
foreach($data as $key=>$row){
if(substr($row['last_name'],0,1)!=$last) echo '<br /><br />'.substr($row['last_name'],0,1).'<br />----------------<br />';
$last = substr($row['last_name'],0,1);
echo $row['last_name'];
}
In your view you could then loop the records and split them up:
$current = '';
foreach ($rows as $r) {
if (!$current || strtolower($r['name'][0]) != $current) {
$current = strtolower($r['name'][0]);
echo strtoupper($current).'<br />---------------';
}
echo $row['name'].'<br />';
}
in your query, try adding something like:
group by substr(last_name,1,1)
i.e.
select substr(last_name,1,1) as alpha, *
from tableName
group by substr(last_name,1,1)
Yes you can achive this using MySql itself
In my case brand_name going to be list out as you expected.
Example :
SELECT id, upper(SUBSTR(brand_name, 1, 1)) AS alpha FROM products WHERE brand_name != '' group by alpha
UNION
SELECT id, upper(SUBSTR(brand_name, 1, 1)) AS alpha FROM products WHERE brand_name != '' order by brand_name COLLATE NOCASE
Result :
A
A Card
A Cef
A Cef O
B
Bacticef Tab
Bacticin
Bactidrox
Bactidrox Kid
........
Hope it will help someone.

Php loop need help?

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 :)
}

Categories