I have been trying to manage duplicate data which is shown to users.
I thought I can add the varibales to arrays and use the function array_unique
I want to be able to manage the rows which contain a duplicate date and split them into different sections for example
if(duplicate.exists == true)
{
//do something to the duplicate row
}
else
{
//do something to the row which isnt a duplicate
}
I cant figure out why array_unique is not working.
Help would be appreciated, Thanks.
$result = mysqli_query($con, "SELECT *
FROM quotes order by DATE asc ");
$index1 = array();
$fact1 = array();
$newDate1 = array();
while ($row = mysqli_fetch_array($result)) {
$index = $row['id'];
$dbdate = $row['date'];
$fact = $row['quote'];
$newDate = date("d-m-Y", strtotime($dbdate));
$index1[] = $fact;
$fact1[] = $fact;
$newDate1[] = $newDate;
}
Then have a function which loops through each array and finds out if a certain date has already exists.
for($i=0; $i<count($index1); $i++) {
echo(array_unique($newDate1));
}
else
{
}
Thats an example of the data that will be in the DB.
It's the id, fact, date example 1, fact, 2015-01-22
1 Steve Jobs unveiled the first Apple #Mac computer and changed technology forever (1984) - 2015-01-24
2 In 2011, the Urban Technology Innovation Center was launched in New York City - 2015-01-25
3 #Bebo was launched a whole decade ago today (2005), who feels old? - 2015-01-26
4 Sun Microsystems was acquired by Oracle Corporation for $7.4 bn (2010) - 2015-01-27
Considering you are sorting your query on date and that makes something a duplicate, all you need to do is track the last date.
$lastdate = '';
while ($row = mysqli_fetch_array($result)) {
$dbdate = $row['date'];
if ($lastdate==$dbdate) {
//duplicate
} else {
//first or unique
}
$lastdate = $dbdate;
}
It can be quicker to do this in SQL
Find the duplicates
SELECT * FROM quotes GROUP BY `date` HAVING COUNT(`date`) > 1 order by DATE asc
Find the non-duplicates
SELECT * FROM quotes GROUP BY `date` HAVING COUNT(`date`) = 1 order by DATE asc
So as noted by the OP, he wants a way to detect duplicates and not remove them.
To detect duplicates you can use something like this, answered in another question.
I would prefer this:
function array_has_dupes($array) {
return count($array) !== count(array_unique($array));
}
Use SQL "count" and "group".
create table z (x varchar(100),y varchar(100));
insert into z values ('a','b');
insert into z values ('a','b');
insert into z values ('a','c');
select x,y,count(*) as count from z group by x,y;
You get values:
+------+------+-------+
| x | y | count |
+------+------+-------+
| a | b | 2 |
| a | c | 1 |
+------+------+-------+
And use it in php code.
Related
I'm using this w3schools way to get data from the database:
$sql = "SELECT num_of_reservations FROM table WHERE date = '$date";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["num_of_reservations"];
}
I have database which looks like this:
id - date - num_of_reservations - name
1 - 2017-02-02 - 3 - somebody
2 - 2017-02-02 - 5 - somebody
3 - 2017-02-02 - 7 - somebody
This works fine if I want to echo rows from the database, but now I need to make form which allows you to make reservation only if there is less than 15 reservations already at the same day. Problem in my current design is that every num_of_reservations row is going to different Array (because of while loop I quess) and I need to make them to + (3+5+7) so I can compare, is the num_of_reservations <=15 If it is I display ticket buying screen and if it's not I tell to pick another day.
You can use another query to get the sum of all reservations:
$sql = "SELECT SUM(num_of_reservations) AS sum_of_reservations FROM table WHERE date = '$date'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
if ($row['sum_of_reservations'] <= 15) {
//display ticket buying screen.
} else {
//tell to pick another day.
}
I have mysql table that looks like this:
id place interest
1 place1 a,b,c
2 place2 c,d,e
3 place1 a,e
4 place2 f
5 place2 f
6 place3 g,h
I need to get unique "place" and "interest" values sorted as per the count.
So, the output for "place" would be
place2(3)
place1(2)
place3(1)
So, the output for "interest" would be
a(2)
c(2)
e(2)
f(2)
b(1)
d(1)
g(1)
h(1)
is there a way to do this in PHP-Mysql?
So, far I have been able to get simple column data
SELECT place,
COUNT( * ) AS num
FROM testtab
GROUP BY place
ORDER BY COUNT( * ) DESC
As mysql is not able to hold arrays, its better to build a new table like this:
interest_id interest_name
1 a
2 b
and another one to keep the relations:
pk id interest_id
1 1 1
2 1 2
which this id is the id of the records in your main table.
With having this, you can easily use:
select count(*) from THIRD_TABLE where id = YOUR_ID
You can do this.
$place = array();
$interests = array();
foreach($rows as $row){
if (!isset($place[$row["place"]])){
$place[$row["place"]] = 0;
}
$place[$row["place"]]++;
$ints = explode(",", $row["interests"]);
foreach($ints as $int){
if (!isset($interests[$int])){
$interests[$int] = 0;
}
$interests[$int]++;
}
}
This will give you the two arrays keyed off of the relevant field with the value being the count. If this is going to be a common action in your application it would make more sense to normalize your data as suggested by AliBZ.
This is for the first result you need
SELECT place,COUNT(interest)
FROM `testtab`
GROUP by place
ORDER BY COUNT(interest) desc
can do this :
$inst_row = '';
foreach($rows as $row){
$inst_row .= $row['interests'];
}
$inst_values = explode(',', $inst_row);
$inst_count = array_count_values($inst_values);
// $inst_count will return you count as you want ,print_r it and format it accordingly
I have a table like following:
id q_id value
------------------------
1 2 5
2 2 NULL
3 2 5
4 2 NULL
5 4 2
6 4 NULL
7 4 2
8 4 NULL
What I want is to get the sum of (for example) all value where q_id = 2
$sq = mysql_query("SELECT SUM(value) AS sum FROM table WHERE q_id = 2)or die(mysql_error());
while($row = mysql_fetch_array($sq)){
$sum = $row['sum'];
}
echo $sum."<br>";
But I'm getting
5
5
But what I want is the sum of the value and expecting 10 instead.
Thank you for helping.
If you're going to loop over the result set anyway, why not just use
SELECT value FROM table WHERE q_id=2
then sum up those values using the while loop? Something like:
while($row = mysql_fetch_array($sq)) {
$sum += $row['value'];
}
echo $sum."<br>";
Edit: also, as Jason McCreary said above, you should look into an alternate method of querying the database. I would suggest searching php.net for "PDO", which is very easy to use.
We can directly sum in the query like
SELECT 5+6 AS addition
Give it a try... You are displaying value, there was missing quote in your code.
$sq = mysql_query("SELECT SUM(value) AS sum FROM `table` WHERE `q_id` = '2'")or die(mysql_error());
while($row = mysql_fetch_assoc($sq))
{
$sum = $row["sum"];
}
echo $sum . "<br>";
$sq="SELECT value FROM table WHERE q_id='".$am."'";
$result=mysqli_query($link,$sq);
while($row=mysqli_fetch_assoc($result)) {
$sum += $row['value'];
}
echo "<p>Sum: ".$sum."</p><br>";
//$am ='2';
//$link -- connection to the data base
Please put $am ='2'; before the select statement and also make sure you have connected to the data base using $link
You will get the total sum according to the value of q_id
I have tested the code and works fine.
You need to add a GROUP BY to your query. Add the following to the end
GROUP BY q_id
Currently I have a code that gets the data from the database and a foreach loop that list all the result. But I want to display one result at a time. Just to warn you, I'm really new to this. Really appreciate your help.
function featured_topics(){
$featureNum = 162;
$query = mysql_query("SELECT *
FROM `topics`
WHERE `country_id` = '$featureNum'");
$numrows = mysql_num_rows($query);
while( $row = mysql_fetch_array($query)){
$featured_topics[] = $row;
}
return $featured_topics;
}
function get_featured_topic(){
$get_topics = featured_topics();
$topic_count = sizeof($get_topics);
$current_topic = $get_topic[$topic_count];
echo $current_topic['topic_id'];
}
function featured_topics(){
$featureNum = 162;
$query = mysql_query("SELECT *
FROM `topics`
WHERE `country_id` = '$featureNum' LIMIT 0,1");
$numrows = mysql_num_rows($query);
$row = mysql_fetch_array($query);
return $row;
}
$result = mysql_result($query, 0, 'column')
0 represents the 0'th row.
You can't do this in the way you want.
SQL rows don't have an intrinsic order, so there's no guarantee that the next time you execute this query the rows will be in the same order. Here is what might happen:
Query result:
points | name
--------------------
23 | Iceland
83 | Georgia
8 | Spain
10 | Argentina
You take the 1st row (Iceland). Then later, you do the same query. You get back this result:
points | name
--------------------
83 | Georgia
23 | Iceland
8 | Spain
10 | Argentina
Whooops! Now you got Iceland again and lost track of Georgia.
Solutions to this dilemma
Grab all the rows at once, cache them, then cycle through them at your leisure. I believe this is the best solution.
Specify some order using "ORDER BY", and be prepared to deal with issues where rows are inserted during your iteration.
I've created a table which approximates to this:
Fruit | Date Purchased | Amount Purchased
----------------------------------------------
Apples | 01-01-10 | 5
Oranges | 01-01-10 | 7
Apples | 02-01-10 | 3
Oranges | 02-01-10 | 2
etc....
I need to end up with the data in the following format though:
Apples (
(01-01-10, 5),
(02-01-10, 3)
)
Oranges (
(01-01-10, 7),
(02-01-10, 2)
)
etc...
The types of fruit are not fixed - more will be added over time, so this would be need to be taken into account.
I've been stuck on this for quite a while now, so any pointers or tips would be really appreciated.
I to lazy to figure out the correct HTML tag to do the tab, but the following code should help you out.
SELECT CONCAT(
s.Fruit, ' (<br/>', '<tab/>',
GROUP_CONCAT(s.DatePlusAmount SEPARATOR ',<br/><tab>'),
'<br/>)<br/>') as FruitLine FROM
(
SELECT Fruit, CONCAT(PDate, ',', IFNULL(sum(amount),0)) AS DatePlusAmount
FROM table1
GROUP BY DATE
) s
GROUP BY Fruit
No loops in php needed.
You can loop through all all your records and add every row to the appropriate array:
Something like:
$fruits = array();
while ($row = get_new_database_row) /* depends on mysql, mysqli, PDO */
{
$fruits[$row['fruit']][] = array($row['date'], $row['amount']);
}
Edit: Based on your codeigniter comments, you either need result_array() or you need to change $row['fruit'] to $row->fruit, $row['date'] to $row->date, etc.
I would do this in two queries:
$sql = "SELECT * FROM tabledata";
$rs = mysql_query($sql);
while( false !== ($r = mysql_fetch_assoc($rs2)))
{
$arr_fruit[ $r['fruit'] ][ $r['date_purchase'] ] = $r['amout'];
}
at this point, you'll end up having associative array that you can further process.
I leave that as an exercise. Come back again when you have problem. But, be sure to bring some code.