PHP Beginner - What am i doing wrong? - php

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 )

Related

Sql statement into an array causing duplicates

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'];
}
}

How to dynamically display links in web pages using PHP

Good day # all.
I've this code snippet which's aim is to display the Exam this user is qualified to take based on the courses registered for. It would display the Exam Name, Date Available, Passing Grade and either Take Exam link if he/she hasn't written or View Result if he/she has written previously.
/*Connection String */
global $con;
$user_id = $_SESSION['user_id']; //user id
$courses = parse_course($user_id); //parse course gets the list of registered courses (Course Codes) in an array
foreach ($courses as $list)
{
$written = false;
$list = parse_course_id($list); //parse_course_id gets the id for each course
$ers = mysqli_query($con, "Select * from exams where course_id = '$list'");
while ($erows = mysqli_fetch_assoc($ers)) {
$trs = mysqli_query($con, "Select * from result_data where user_id = '$user_id'");
while ($trows = mysqli_fetch_assoc($trs)) {
if ($trows['user_id'] == $user_id && $trows['exam_id'] == $erows['exam_id'])
$written = true;
else
$written = false;
}
if($written)
{
echo "<tr><td>".$erows['exam_name']."</td><td>".$erows['exam_from']." To ".$erows['exam_to']."</td><td>".$erows['passing_grade']."%</td><td>".'View Result '."</td></tr>";
$written = false;
}
else
{
echo "<tr><td>".$erows['exam_name']."</td><td>".$erows['exam_from']." To ".$erows['exam_to']."</td><td>".$erows['passing_grade']."%</td><td>".'Take Exam '."</td></tr>";
$written = false;
}
}
}
But It only displays one View Result entry even if I've taken more than one exam. It shows the recent entry. Please what am I missing?
Untested, but here's how I would do it.
I've assumed $user_id is an integer. I'm a bit worried about it being used in SQL without any sanitization. I can't guarantee anything else you're doing is secure either because I can't see your other code. Please read: http://php.net/manual/en/security.database.sql-injection.php
(Oh I see someone already commented on that - don't take it lightly!)
Anyway, my approach would be to collect the user's written exam IDs into an array first. Then loop through the available exams and check each exam id to see if it's in the array we made earlier.
I wouldn't bother looking into the join advice unless you find this is performing poorly. In many systems it would be common to have 3 functions in this situation, one that generates $users_written_exam_ids ones that pulls up something like $all_available_exams and then this code which compares the two. But because people are seeing both queries here together there is a strong temptation to optimize it, which is cool but you probably just want it to work :)
<?php
global $con;
// Get the user id. Pass through intval() so no SQL injection is possible.
$user_id = intval($_SESSION['user_id']);
// Parse course gets the list of registered courses (Course Codes) in an array
$courses = parse_course($user_id);
foreach ($courses as $list)
{
// Gets the id for each course
$list = parse_course_id($list);
$users_written_exam_ids = array();
$trs = mysqli_query($con, "SELECT exam_id FROM result_data WHERE user_id = '$user_id'");
while ($trows = mysqli_fetch_assoc($trs))
{
$users_written_exam_ids[] = $trows['exam_id'];
}
$ers = mysqli_query($con, "SELECT * FROM exams WHERE course_id = '$list'");
while ($erows = mysqli_fetch_assoc($ers)) {
echo '<tr><td>' . $erows['exam_name'] . '</td><td>' . $erows['exam_from']
. ' To ' . $erows['exam_to'] . '</td><td>' . $erows['passing_grade']
. '%</td><td>';
if (in_array($erows['exam_id'], $users_written_exam_ids))
{
echo 'View Result';
}
else
{
echo 'Take Exam';
}
echo '</td></tr>';
}
}

How to break down a php array with levels?

I have a MySQL table with stock information including what main industry sector and sub sector a stock belongs to (for example the Coca-Cola stock belongs to the industry sector "Consumer Goods" and to the sub sector "Beverages - Soft Drinks".
$SQL = "SELECT name, industrysector, subsector FROM Stocks WHERE economic_indicator_type = 'Stock' GROUP BY industrysector, subsector, name";
$result = mysql_query($SQL) or die ("Error in query: $SQL. " . mysql_error());
while ($row = mysql_fetch_row($result)) {
$stocks[$i]['name'] = $row[0];
$stocks[$i]['industrysector'] = $row[1];
$stocks[$i]['subsector'] = $row[2];
$i++;
}
$stocksTotals = array();
foreach($stocks as $amount) {
$stocksTotals[$amount['industrysector']] = $stocksTotals[$amount['industrysector']].", ".$amount['name'];
}
foreach($stocksTotals as $name => $amount) { echo $name.": ".substr($amount,1)."<br>"; }
My problem is that I don't get the code to handle the third level. I want to first output all of the industry sectors (Basic material for example), then all subsectors (Basic Resources for example) for each industry sector, then all names of the stocks corresponding to each subsector.
Currently I only get industry sector and then the stock name, because I fail to understand how to handle this in the array handling code.
Any advise would be highly appreciated! I have put a image here (http://imageshack.us/photo/my-images/853/mysqltophp.gif/) for better reference.
Thanks!
the foreach loop needs to be like this:
//considering you want the value as "$amount['industrysector'], $amount['name']"
foreach($stocks as $amount) {
// $stocksTotals[$amount['industrysector']] = $amount['industrysector'] .", ".$amount['name'];
echo $amount['industrysector'].": "."$amount['industrysector'], $amount['name']"."<br>";
}
you dont need another foreach loop.
Edit: you would need to change the way you fetch your rows too,
while ($row = mysql_fetch_assoc($result)) {
$stocks[$i]['name'] = $row['name'];
$stocks[$i]['industrysector'] = $row['industrysector'];
$stocks[$i]['subsector'] = $row['industrysector'];
$i++;
}
foreach($stocks as $amount) {
$output = "$amount['industrysector'] : $amount['industrysector'], $amount['subsector']";
if( $amount['name'] !== '' )
$output .= "<br>" . $amount['name'];
";
}

PHP Function Dependent on presence of MySQL data entry

I code a weekly trivia program for one of my clients through facebook.
I have a bit of code commented out where we display the winner when we need to. Currently I just remove the comment brackets and update when it's time to display. I'm trying to make this so someone non-savvy can handle updates so I've moved my code into an include:
winner-display.php
I am trying to write a function so that if the winner is set in MySQL, it includes the file in-line, and if the winner field is empty in the database, it does not.
Here is what I have so far, any ideas?
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != 'null') {
include('../includes/winner-display.php');
} else {
}
?>
Ok, thanks for helping guys, got it to work as:
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
foreach ($row as $field) {
if ($field != null) {
include('../includes/winner-display.php');
}
}
}
?>
You can definitely put an include within an if. That solution that you posted should work as you would like it to, although I personally would have used a function instead of a completely separate file to include (although that is personal preference).
All you have to do to make it work is remove the quotes around 'null'.
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = $target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
$displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != null) {
include('../includes/winner-display.php');
}
?>
Keep in mind that if your query returns more than one row, only the last row will be retained. I don't know if that is the functionality you want (in which case, there are some changes you could make, just ask me to edit my answer), but I didn't change that.

While loop only retrieving one result

UPDATE: Still can't seem to figure it out. If anyone can lend a hand, it would be appreciated ^^.
I am having a problem and I'm not sure where my code is breaking down. I have a 'follow' function where you can follow different registered users. Their userID's of who you followed are stored in an array (follower_array). It's retrieving each member from the array, but of each member that's followed instead of displaying all the content, it's only displaying the 1 latest one from each member.
$broadcastList= "";
if ( $follower_array != "" ) {
$followArray = explode(",", $follower_array);
$followCount = count($followArray);
$i = 0;
$broadcastList .= "<table>";
foreach( $followArray as $key => $value ) {
$i++;
$sqlName = mysql_query("
SELECT username, fullname
FROM members
WHERE id='$value'
LIMIT 1
") or die ("error!");
while ( $row = mysql_fetch_array($sqlName) ) {
$friendUserName = substr($row["username"],0,12);
}
$sqlBroadcast = mysql_query("
SELECT mem_id, bc, bc_date, device
FROM broadcast
WHERE mem_id='$value'
ORDER BY bc_date ASC
LIMIT 50
") or die ("error!");
while ( $bc_row = mysql_fetch_array($sqlBroadcast) ) {
$mem_id = $bc_row['mem_id'];
$bc = $bc_row['bc'];
$dev = $bc_row['device'];
$bc_date = $bc_row['bc_date'];
$broadcastList .= "<td><a href='member.php?id=' .$value. ''>
$friendUserName</a> • $when_bc • Via: $dev <b>$bc</b></td></tr>";
}
broadcastList .= "</table>";
}
}
So, it's retrieving the members entirely, but not more than their single latest "broadcast." Any insight would be appreciated.. thank you!
Here's what's happening:
while( $row = some_next_result_function() ){
$result = $row["thing"];
}
Is going to overwrite $result every time, so you'll only end up with the last result.
You need to make a list and append to it instead.
I'm gonna take a shot in the dark:
$broadcastList .= "<td><a href='member.php?id=' .$value. ''>
$friendUserName</a> • $when_bc • Via: $dev <b>$bc</b></td></tr>";
That line pretty much misses a starting "tr" element. Are you sure the content isn't shown simply because of the faulty html markup?
Also:
broadcastList .= "</table>";
You're missing the $ there ;).
I don't know if this fixes it or even helps you; but I sure hope so :). Alternatively; you can also check the HTML source to see if the entries really aren't there (see first remark).

Categories