Sql statement into an array causing duplicates - php

this is my first time using the site. I need some help. When I run this code and get the output I get duplicated lines of data. So for instance a member maybe on the list 3 - 4 times depending on how many years he has gone to the events. I need to somehow combine any similar data into one row, if that makes sense? So John Doe should not be on the list 7 times just once with all the years he has gone.
$query_mem = "SELECT m.id, m.prefix, m.first_name, m.middle_name, m.last_name, m.suffix, m.member_class, m.jurisdiction_associated,
event.year,
m_event.attend
FROM members AS m, event AS event, members_event AS m_event $where
AND m.member_class IN (1,3)
AND m.id = m_event.codigo_usuario AND m_event.type_event = event.codigo_inscricao
ORDER BY event.year, m.jurisdiction_associated, m.last_name, m.first_name";
$retorno_mem = $conexao->query($query_mem);
if(($conexao->errorCode() == '0') && ($retorno_mem->rowCount() > 0))
{
while($registros_mem = $retorno_mem->fetch(PDO::FETCH_ASSOC))
{
$prefix=$fname=$mname=$lname=$suffix=$address_1=$address_2=$city=$state=$zip=$country=$org=$campaign=NULL;
$member_id = ($registros_mem["id"]);
$prefix = ($registros_mem["prefix"]);
$fname = ($registros_mem["first_name"]);
$mname = ($registros_mem["middle_name"]);
$lname = ($registros_mem["last_name"]);
$suffix = ($registros_mem["suffix"]);
$class = getMemberClassName($conexao,$registros_mem["member_class"]);
$jurisdiction = getJurisdictionName($conexao,$registros_mem["jurisdiction_associated"]."000");
$year = ($registros_mem["year"]);
$attendance = getMemberAttendanceName($conexao,$registros_mem["attend"]);
$data1[] = array(
''.utf8_encode((int)$member_id).'',
''.utf8_encode($prefix).'',
''.utf8_encode($fname).'',
''.utf8_encode($mname).'',
''.utf8_encode($lname).'',
''.utf8_encode($suffix).'',
''.utf8_encode($class).'',
''.utf8_encode($jurisdiction).'',
''.utf8_encode($year).'',
''.utf8_encode($attendance).'',
);
}
}

You can use the member's ID as the array key to see if he's already been, and if so just add to the year field. Something like this:
while($registros_mem = $retorno_mem->fetch(PDO::FETCH_ASSOC))
{
if ( ! array_key_exists( $registros_mem['id'], $data1)
{
// We need to make year an array so it can hold multiple years.
$registros_mem['year'] = [$registros_mem['year']];
$data1[$registros_mem['id']] = $registros_mem;
} else {
$data1[$registros_mem['id']]['year'][] = $registros_mem['year'];
}
}

Related

PHP Beginner - What am i doing wrong?

First of all, im a beginner so please excuse me if i don't mention things that could be important.
I have Sellers, that are in different countries in the world. Each country belong to a continent. Im trying to:
get the seller name
Fetch Database to see in what countries (China,Italy,Germany...) he offers his goods.
Then fetch another database and see in what continents (ASIA,EU) belong each country
Store the countries (Italy,Germany) to a variable $country_eu and $country_asia (China). So later i will add this variables to update database fields.
if($continent == 'ASIA') is not included in the code YET since i take one by one the steps. I want to make first EU work, then i figure out the rest.
include_once('../db.php');
session_start();
$seller_name = $_SESSION['seller_name'];
echo $seller_name;
if (!empty($_POST['flag_image'])){
$flags_array = $_POST['flag_image'];
$flags_string = implode(",",$flags_array);
}else{
$flags_string = '';
}
$cont_eu = '';
// Assign Flags to Continents
foreach ($flags_array as $flag_image){
$qry_find_flag_continent = " SELECT continent FROM flags WHERE flag_image = '$flag_image' ";
$result = $dbdetails->query($qry_find_flag_continent);
while($row = mysqli_fetch_array($result)) {
$continent = $row["continent"];
if ($continent == 'EU') {
$cont_eu .= $flag_image;
}
}
echo $cont_eu;
The problem with my code is that when i echo $cont_eu is giving me just 1 result(Germany) and not the EXPECTED (Italy,Germany)
Thank you all for your precious time and attempts to help. Here is the new code that works great.
include_once('../db.php');
session_start();
$seller_name = $_SESSION['seller_name'];
echo $seller_name.'<br>';
if (!empty($_POST['flag_image'])){
$flags_array = $_POST['flag_image'];
$flags_string = implode(",",$flags_array);
} else {$flags_string = '';}
// Assign Flags to Continents
foreach ($flags_array as $flag_image){
$qry_find_flag_continent = " SELECT continent FROM flags WHERE flag_image = '$flag_image' ";
$result = $dbdetails->query($qry_find_flag_continent);
while($row = mysqli_fetch_array($result)) {
$continent = $row["continent"];
if($continent == 'EU'){ $eu_flags_array[] = $flag_image;}
}
}
print_r($eu_flags_array); //Gives me Array ( [0] => Germany.png [1] => Italy.png )

PHP loop not returning all possible MySQL query results

I am new to php & MySQL.
I have a db that contains two tables called person (property owner) and property.
There is a one-to-many relationship between the tables. For instance, a person can own many properties.
I am using php to retrieve data from the db (I have already established a connection with the db).
What I am trying to achieve is this: if a query is carried out for a person's name - (whether it is fname or lname) - then a list of all the properties owned by this person will be displayed in my search results form. The output will be shown as lname, fname, property number, property road, property zipcode.
However, with this code I am only getting two results output per property owner name. :
$request = mysql_query("SELECT person.fname, person.lname, property.number, property.road, property.zipcode,
FROM person p
INNER JOIN property py
ON p.id = py.p_id
WHERE p.fname LIKE '%$search%'
OR p.lname LIKE '%$search%'
ORDER BY p.lname");
$number = mysql_num_rows($request);
if ($number == 0){
$result .= 'No results'.' '.$search;
} else {
$propertyinfo= array();
$count = 0;
$real = false;
$real_within_array = 0;
while ($nrow = mysql_fetch_array($query)){
$lname = $nrow['lname'];
$real = false;
for ($l = 0; $l < count($propertyinfo); $l++)
{
if ($propertyinfo[$l][0] == $lname)
{
$real = true;
$real_within_array = $l;
break;
}
}
if ($real)
{
$fname = $nrow['fname'];
$lname = $nrow['lname'];
$number = $nrow['number'];
$road = $nrow['road'];
$zipcode = $nrow['zipcode'];
$propertyinfo[$real_within_array][1][1] = $fname;
$propertyinfo[$real_within_array][2][1] = $lname;
$propertyinfo[$real_within_array][3][1] = $number;
$propertyinfo[$real_within_array][4][1] = $road;
$propertyinfo[$real_within_array][5][1] = $zipcode;
}
else
{
// Get all the data from the row.
$fname = $nrow['fname'];
$lname = $nrow['lname'];
$number = $nrow['number'];
$road = $nrow['road'];
$zipcode = $nrow['zipcode'];
$propertyinfo[$real_within_array][1] = $fname;
$propertyinfo[$real_within_array][2]= $lname;
$propertyinfo[$real_within_array][3][0] = $number;
$propertyinfo[$real_within_array][4][0] = $road;
$propertyinfo[$real_within_array][5][0] = $zipcode;
$count++;
}
}
Example: Adam Smith owns 4 properties, but I will only get a result of two of his properties instead of all 4 in a list.
Please help. I have tried my very best to sort this out but I seem to have stumbled upon a difficult problem.
Your help is much appreciated.
Thank you in advance.
I think it's a logical error;
when you defined $propertyinfo=array(); it's size is 0, therefore the code withing the block of
for ($l =0; $l< count($propertyinfo); $l) will only start running after some values has been assigned to $propertyinfo.
What is $uqery? Maybe:
while ($nrow = mysql_fetch_array($request)){
You would see this with:
error_reporting(E_ALL);
ini_set('display_errors', '1');
As for all the other stuff it's impossible to tell without knowing what $propertyinfo looks like. Very convoluted looking so I don't follow.
Try using while(($nrow=mysql_fetch_assoc($query))!=null) to cycle on your query results

Updating a row number which has been randomised

So I currently have a random number being generated in PHP and I want to know how I go about updating the row number in my selected table. Code below:
$sxiq = mysql_query("SELECT * FROM `starting_eleven` WHERE `team_id`=$uid");
$sxir = mysql_fetch_row($sxiq);
$first = rand(1,11);
$stat_changed = rand(11,31);
$up_or_down = rand(1,2);
if ($up_or_down == 1) {
$player_name = explode(" ", $sxir[$first]);
$fn = $player_name[0];
$ln = $player_name[1];
$statq = mysql_query("SELECT * FROM `players` WHERE `first_name`=$fn AND `last_name`=$ln AND `user_id`=".$_SESSION['user_id']);
$statr = mysql_fetch_row($statq);
$stat = $statr[0];
}
I would like to update the row $stat_changed from the database, but I'm not sure if this is possible without doing a long if statement, telling the code if $stat_changed = 13 $stat = pace or something along those lines, but if this is the way it must be done then I'll have to. Just thought I'd see if there was any other simpler ways of doing this.
Thanks in advance
if ($stat_changed == 13) {
//insert UPDATE statement here
}

MySQL sorting with PHP

I'm trying to accomplish the following situation:
$mysql_query = "
SELECT *
FROM st_users
WHERE
`user_comp_supervisor_id` = '$team_supervisor' AND
`user_exempt_from_goals` = '0'
ORDER BY 'calculate_progress_percent()' ASC
";
I know that I can't accomplish ordering by a function in a MySQL statement, but I'm trying to figure out how to take all the returned records, and then order them in order of highest to lowest from a php function result. Any ideas would be greatly appreciated; I've been trying to wrap my head around this for a few hours now... :-(
function diy_calc_progress_percent($user_id,$period_id,$period_week_number)
{
$this->user_id = $user_id;
$this->period_id = $period_id;
$this->period_week_number = $period_week_number;
if ($this->period_week_number == 1)
{
$this->week_id = mysql_result( mysql_query(" SELECT `period_week_one` FROM `st_comp_periods` WHERE `period_id` = '$this->period_id' "),0 );
}
else if ($this->period_week_number == 2)
{
$this->week_id = mysql_result( mysql_query(" SELECT `period_week_two` FROM `st_comp_periods` WHERE `period_id` = '$this->period_id' "),0 );
}
else
{
echo "Week number not valid.";
exit();
}
$this->week_start_date = mysql_result( mysql_query(" SELECT `week_start_date` FROM `st_comp_weeks` WHERE `week_id` = '$this->week_id' "),0 );
$this->week_end_date = mysql_result( mysql_query(" SELECT `week_end_date` FROM `st_comp_weeks` WHERE `week_id` = '$this->week_id' "),0 );
$this->user_department = $this->user_info($this->user_id,"user_comp_department_id");
$this->user_week_diy_goal = mysql_result( mysql_query(" SELECT `goal_diy_department` FROM `st_comp_department_goals` WHERE `goal_department_id` = '$this->user_department' AND `goal_week_id` = '$this->week_id' "),0 );
$this->calc_totals_result = mysql_query("SELECT SUM(record_total_diy_revenue) AS user_week_total FROM `st_entered_records` WHERE `record_user_id` = '$this->user_id' AND `record_date` BETWEEN '$this->week_start_date' AND '$this->week_end_date'");
$this->calc_totals_row = mysql_fetch_assoc($this->calc_totals_result);
$this->user_week_total = $this->calc_totals_row['user_week_total'];
$this->user_week_one_percent = ($this->user_week_total / $this->user_week_diy_goal) * 100;
$this->user_week_one_percent = number_format( (float)$this->user_week_one_percent, 2, '.', '' );
return $this->user_week_one_percent;
}
You probably will have to do some array juggling.
First get all your entries FROM st_users into a first array (mysql_query)
Then you could run through that array, and for each entry you do the calculate_progress_percent() and build up a second array in which you could add the additional info ("user_progress_percent").
After this you can sort the new array ba your new info ("user_progress_percent").
And here is some quick and dirty code-suggestions – code is however not tested… of course…:)
First:
$mysql_query = "SELECT * FROM st_users
WHERE `user_comp_supervisor_id`='$team_supervisor' AND
`user_exempt_from_goals` = '0'";
Then something like this:
$i = 0;
while($tmp = mysql_fetch_array($mysql_query)) {
$my_second_array[$i]['user_id'] = $tmp['user_id'];
$user_id = $my_second_array[$i]['user_id'];
diy_calc_progress_percent($user_id,$period_id,$period_week_number);
$my_second_array[$i]['user_result'] = $diy_calc_progress_percent_result;
$i++;
}
And then sorting that second array should be possible as described here:
Sort Multi-dimensional Array by Value
…hope this helps at some point…

Exhausting Memory - Tried Fixing Loops, Still Does Not Work

I'm currently experiencing a memory usage issue - but I cannot figure out where. I've tried replacing some of my foreach loops with for loops or by issuing another query to the DB, but I am still gettting the same error - "Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes) in on line 109". Can anyone provide some insight as to what may be causing the issue? Thank you!
Code after #Patrick 's answer:
$participating_swimmers = array();
$event_standings = array();
$qualifying_times = array();
$events = array();
$current_event = '';
$select_times_sql = "SELECT event, time, name, year, team, time_standard, date_swum
FROM demo_times_table
WHERE sex = 'M' AND (time_standard = 'A' OR time_standard = 'B')
ORDER BY event, time ASC";
$select_times_query = mysql_query($select_times_sql);
//Create array with the current line's swimmer's info
while ($swimmer_info = mysql_fetch_assoc($select_times_query)) {
if($current_event != $swimmer_info['event']){
$events[] = $current_event = $swimmer_info['event'];
}
//Create array with the current line's swimmer's info
$swimmer_info["time"] = $select_times_row['time'];
$swimmer_info["name"] = $select_times_row['name'];
$swimmer_info["year"] = $select_times_row['year'];
$swimmer_info["team"] = $select_times_row['team'];
$swimmer_info["time_standard"] = $select_times_row['time_standard'];
$swimmer_info["date_swum"] = $select_times_row['date_swum'];
//Create "Top 8" list - if more than 8 A cuts, take them all
if (($swimmer_info["time_standard"] == "A") || ($swimmer_info["time_standard"] == "B")) {
//Check if there are 8 or less entries in the current event, or if the swim is an A cut
if ((count($event_standings[$current_event]) < 8) || ($swimmer_info["time_standard"] == "A")) {
//Add swimmer to the list of invites
$event_standings[$current_event][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
} else {
//Add the qualifying time that did not fit into the list to a list of qualifying times
$qualifying_times[$current_event][] = $swimmer_info;
}
}
}
//Sort each array of times in descending order
arsort($event_standings);
arsort($qualifying_times);
$num_of_swimmers = count($participating_swimmers);
while ($num_of_swimmers < 80) {
foreach ($events as $loe) {
$num_of_qualifying_times = count($qualifying_times[$loe]);
$swimmer_info = $qualifying_times[$loe][$num_of_qualifying_times-1];
$event_standings[$loe][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
//Remove time from array of qualifying times
unset($qualifying_times[$loe][$num_of_qualifying_times-1]);
}
$new_num_of_swimmers = count($participating_swimmers);
if($num_of_swimmers == $new_num_of_swimmers) break;
else $num_of_swimmers = $new_num_of_swimmers;
}
arsort($event_standings);
arsort($qualifying_times);
foreach($event_standings as $loe => $event_swimmer) {
echo "<h1>",$loe,"</h1><br />";
foreach ($event_swimmer as $es) {
echo $es["time"]," ",$es["name"]," ",$es["team"],"<br />";
}
}
Large data in database is the problem 95% !
- try using limit x,y in your queries , and put those queries in some loop .
- see http://php.net/manual/en/function.mysql-free-result.php it might help
<?php
$participating_swimmers = array();
$event_standings = array();
$qualifying_times = array();
$select_times_sql = "SELECT *
FROM demo_times_table
WHERE sex = 'M'
ORDER BY time ASC";
$select_times_query = mysql_query($select_times_sql);
while ($select_times_row = mysql_fetch_assoc($select_times_query)) {
//Create array with the current line's swimmer's info
$swimmer_info["time"] = $select_times_row['time'];
$swimmer_info["name"] = $select_times_row['name'];
$swimmer_info["year"] = $select_times_row['year'];
$swimmer_info["team"] = $select_times_row['team'];
$swimmer_info["time_standard"] = $select_times_row['time_standard'];
$swimmer_info["date_swum"] = $select_times_row['date_swum'];
//Create "Top 8" list - if more than 8 A cuts, take them all
if (($swimmer_info["time_standard"] == "A") || ($swimmer_info["time_standard"] == "B")) {
//Check if there are 8 or less entries in the current event, or if the swim is an A cut
if ((count($event_standings[$current_event]) < 8) || ($swimmer_info["time_standard"] == "A")) {
//Add swimmer to the list of invites
$event_standings[$current_event][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
} else {
//Add the qualifying time that did not fit into the list to a list of qualifying times
$qualifying_times[$current_event][] = $swimmer_info;
}
}
}
mysql_free_result($select_times_query);
//Sort each array of times in descending order
arsort($event_standings);
arsort($qualifying_times);
$num_of_swimmers = count($participating_swimmers);
$sql = "SELECT DISTINCT(event)
FROM demo_times_table
WHERE sex = 'M' limit 80";
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
$loe = $row['event'];
$num_of_qualifying_times = count($qualifying_times[$loe]);
$event_standings[$loe][] = $qualifying_times[$loe][$num_of_qualifying_times-1];
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $qualifying_times[$loe][$num_of_qualifying_times]["name"];
$condensed_swimmer_info["year"] = $qualifying_times[$loe][$num_of_qualifying_times]["year"];
$condensed_swimmer_info["team"] = $qualifying_times[$loe][$num_of_qualifying_times]["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
//Remove time from array of qualifying times
unset($qualifying_times[$loe][$num_of_qualifying_times-1]);
}
$num_of_swimmers = count($participating_swimmers);
mysql_free_result($query);
arsort($event_standings);
arsort($qualifying_times);
$sql = "SELECT DISTINCT(event)
FROM demo_times_table
WHERE sex = 'M'";
$query = mysql_query($sql);
while ($row = mysql_fetch_assoc($query)) {
$loe = $row['event'];
echo "<h1>".$loe."</h1><br />";
foreach ($event_standings[$loe] as $es) {
echo $es["time"]." ".$es["name"]." ".$es["team"]."<br />";
}
}
/*
foreach ($participating_swimmers as $ps) {
echo $ps["name"]."<br /><br />";
}
echo "<br /><br />";
*/
?>
Instead of doing a query within a query, with the potential for logic holes that create a never-ending loop, you can condense it into a single query. For your first block, both loops are just checking for the current event and the sex of the participant, right? So:
$result = SELECT * FROM <my database> WHERE sex = 'M' ORDER BY time ASC
Then you can pull whichever rows you want during the while ($row = mysql_fetch_assoc($result)) loop and compensate for non-distinct values in another way.
One other source of the never-ending loop could be in the block where you sort the qualifying times. You're using "unset" after each, which could be getting the pointer stuck. You could try adding array_values($qualifying_times) after the unset to reindex the array.
Frist off, lose the SELECT DISTINCT like so:
$events = array()
$current_event = '';
$select_times_sql = "SELECT event, time, name, year, team, time_standard, date_swum
FROM demo_times_table
WHERE sex = 'M' AND (time_standard = 'A' OR time_standard = 'B')
ORDER BY event, time ASC";
$select_times_query = mysql_query($select_times_sql);
//Create array with the current line's swimmer's info
while ($swimmer_info = mysql_fetch_assoc($select_times_query)) {
if($current_event != swimmer_info['event']){
$events[] = $current_event = $swimmer_info['event'];
}
//Create "Top 8" list - if more than 8 A cuts, take them all
//Check if there are 8 or less entries in the current event, or if the swim is an A cut
This also loses a bit of redundant code, and can speed up the final output (note the commas in the echo statements - the string doesn't need to be concatenated before it is spat out)
foreach($event_standings as $loe => $event_swimmer) {
echo "<h1>",$loe,"</h1><br />";
foreach ($event_swimmer as $es) {
echo $es["time"]," ",$es["name"]," ",$es["team"],"<br />";
}
}
The final problem lies in the second while loop, where the info being put into $condensed_swimmer_info doesn't have the -1 in place, thus is always blank, and $num_of_swimmers never rises to more than 1 over its original value:
while ($num_of_swimmers < 80) {
foreach ($events as $loe) {
$loe = $row['event'];
$num_of_qualifying_times = count($qualifying_times[$loe]);
$swimmer_info = $qualifying_times[$loe][$num_of_qualifying_times-1];
$event_standings[$loe][] = $swimmer_info;
//Keep only the identifying information about the swimmer
$condensed_swimmer_info["name"] = $swimmer_info["name"];
$condensed_swimmer_info["year"] = $swimmer_info["year"];
$condensed_swimmer_info["team"] = $swimmer_info["team"];
//Check if swimmers name already appears in list
if (!in_array($condensed_swimmer_info, $participating_swimmers)) {
//It is a unique user - add them to the list
$participating_swimmers[] = $condensed_swimmer_info;
}
//Remove time from array of qualifying times
unset($qualifying_times[$loe][$num_of_qualifying_times-1]);
}
$new_num_of_swimmers = count($participating_swimmers);
if($num_of_swimmers == $new_num_of_swimmers) break;
else $num_of_swimmers = $new_num_of_swimmers;
}

Categories