Fetching only first row value in Database - php

We are trying to fetch value from database & display related value for all rows.
but code is fetching only first row value in DB & displaying same value for all rows.
Database
Site
function getDesignerCollection()
{
$i = 0;
foreach($order as $orderData)
{
$orderitems = $orderData['dproduct_id'];
$orderitemsarray = explode(",", $orderitems);
$k = 0;
while ($k < count($orderitemsarray))
{
if($data['dpaid_status']=='P'){$dpaid_status='Paid';}
if($data['dpaid_status']=='U'){$dpaid_status='Unpaid';}
if($data['dpaid_status']=='R'){$dpaid_status='Returned';}
if($data['dpaid_status']==''){$dpaid_status='';}
if ($orderitemsarray[$k] != '0')
{
$stmtorders = $user_home->runQuery("SELECT * FROM order_details");
$stmtorders->execute(array(
":dorder_id" => $orderData['entity_id']
));
$roworders = $stmtorders->fetch(PDO::FETCH_ASSOC);
if ($roworders['dproduct_id'] == '')
{
$dorderStatus = "Unpaid";
}
else
{
$dorderStatus = $roworders['dpaid_status'];
}
$responce[] = array(
$orderData->getIncrementId() ,
$orderData->getIncrementId() ,
$orderitemsarray[$k],
$dorderStatus
);
}
$k++;
$i++;
}
}
echo json_encode($responce);
}
full code : http://pastebin.com/GnT980nL

You need use fetchAll() instead fetch()
http://php.net/manual/ru/pdostatement.fetchall.php
Your function must looks like:
function getDesignerCollection() {
global $is_admin;
$user_home = new USER();
require_once '../../app/Mage.php';
Mage::app();
$stmts = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmts->execute(array(
":uid" => $_SESSION['userSession']
));
$rows = $stmts->fetchAll(PDO::FETCH_ASSOC);
}
Now in $rows you have array of associative arrays.

Related

PDO Update 1 column multiple rows with array

I am struggling to workout a good method to update one column of my wcx_options table.
The new data is sent fine to the controller but my function isn't working at all.
I assumed i could loop through each column by option_id updating with the values from the array.
The database:
I update the option_value column with the new information via a jQuery AJAX Call to a controller which then calls a function from the backend class.
So far i have the following code:
if(isset($_POST['selector'])) {
if($_POST['selector'] == 'general') {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& $_POST['token'] === $_SESSION['token']){
$site_name = $_POST['sitename'];
$site_url = $_POST['siteurl'];
$site_logo = $_POST['sitelogo'];
$site_tagline = $_POST['sitetagline'];
$site_description = $_POST['sitedescription'];
$site_admin = $_POST['siteadmin'];
$admin_email = $_POST['adminemail'];
$contact_info = $_POST['contactinfo'];
$site_disclaimer = $_POST['sitedisclaimer'];
$TimeZone = $_POST['TimeZone'];
$options = array($site_name, $site_url, $site_logo, $site_tagline, $site_description, $site_admin, $admin_email,$contact_info, $site_disclaimer, $TimeZone);
// Send the new data as an array to the update function
$backend->updateGeneralSettings($options);
}
else {
$_SESSION['status'] = '<div class="error">There was a Problem Updating the General Settings</div>';
}
}
}
This is what i have so far in terms of a function (It doesnt work):
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$where = array('option_id' => $i);
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$where'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
With the given DB-layout i'd suggest to organize your data as assiciative array using the db fieldnames, like:
$option = array(
'site_name' => $_POST['sitename'],
'site_url' => $_POST['siteurl'],
// etc.
'timeZone' => $_POST['TimeZone']
);
And than use the keys in your query:
public function updateGeneralSettings($options) {
foreach($options as $key => $value) {
$this->queryIt("UPDATE wcx_options SET option_value='$value' WHERE option_name='$key'");
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}
}
(However, are you sure, you do not want to have all options together in one row?)
Change your query, you try to use an array as where condition. In the syntax you used that won't work. Just use the counter as where condition instead of define a $where variable. Try this:
public function updateGeneralSettings($options) {
$i = 1;
foreach($options as $option_value) {
$this->queryIt("UPDATE wcx_options SET option_value='$option_value' WHERE option_id='$i'");
$i++;
}
if($this->execute()) {
$_SESSION['success'] = 'Updated General Settings Successfully';
}
}

How to loop through an array and add to it in JSON

I have an array containing several variables from my sql database.
{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"}, {"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}
I have an additional variable called $score that uses information from the database to calculate this score. I want to know how I can loop through and add the correct score to each country in the array.
My Original Code:
$row = $res->fetchRow();
$resGold = $row['gold'];
$resSilver = $row['silver'];
$resBronze = $row['bronze'];
$resGdp = $row['gdp'];
$resPopulation = $row['population'];
$resCountry = $row['country_name'];
$gold_score = ($resGold * $gold_value);
$silver_score = ($resSilver * $silver_value);
$bronze_score = ($resBronze * $bronze_value);
if($population == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resPopulation);
}
else if($gdp == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resGdp);
}
$result = $res->fetchAll();
$result[] = array('score' => $score);
echo json_encode($result);
Your code will be something like this:
$json_data = '{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"},
{"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}';
$countries_info_new = array();
$countries_info = json_decode($json_data);
foreach($countries_info as $country_info){
$country_info['score'] = Get_country_score($country_info['country_name']);
$countries_info_new[]=$country_info;
}
$new_json_data = json_encode($countries_info_new);

function returning only once, why?

During my coding I really got stuck into this problem.
I ran a foreach loop and for every item I had to get a certain value from a function.
But I got only one returned. I could not figure out what was happening. I hope you guys surely will.
Below is the short version of my program.
Database structure is given at last.
<?php
function opendb() {
mysql_connect("localhost", "root", "root");
mysql_select_db("something_db");
}
function sql_query($sql) {
$datas = array();
if ($res = mysql_query($sql)) {
$x = 0;
while ( $data = mysql_fetch_assoc($res) ) {
$datas[$x] = $data;
$x += 1;
}
}
return $datas;
}
function get_parent_id($table, $parent, $cid) {
// cid=>child id
$sql = "SELECT * FROM $table WHERE id=$cid";
$datas = sql_query($sql);
$pid = $datas[0]['parent'];
$p_id = $datas[0]['id'];
if ($pid != 0) {
get_parent_id($table, $parent, $pid);
} else {
return $p_id;
}
}
opendb();
$datas_pkg = sql_query("SELECT * FROM tbl_packages WHERE 1");
foreach ( $datas_pkg as $data_pkg ) {
echo $data_pkg['destination_id'] . '-->';
echo $parent_id = get_parent_id('tbl_destinations', 'parent', $data_pkg['destination_id']);
echo '<br/>';
}
?>
Database structure..
tbl_destinations
+--------+-------------------------+-----------+
| id(int)|destination_name(Varchar)|parent(int)|
+--------+-------------------------+-----------+
tbl_packages
+-------+---------------------+-------------------+
|id(int)|package_name(varchar)|destination_id(int)|
+-------+---------------------+-------------------+
If I did not clear my question please let me know so that I can help you to help me.
if($pid!=0)
{
get_parent_id($table,$parent,$pid);
}
You call the function, but never use its value.

Array showing only first result good

I try to write this code on few ways, but always the result is good only for first team all other results are bad.
When I put id of some other club instead of $id I get the good result for that team but than is only one row, I want to show all 20 teams.
<table>
<thead><tr><th>Name</th><th>Played</th><th>0,5</th><th>1,5</th><th>2,5</th>
<th>3,5</th><th>4,5</th></tr></thead>
<tbody>
<?php
$teams = mysql_query("select * from teams");
$num_teams = mysql_num_rows($teams);
while ($group = mysql_fetch_row($teams)) {
$id_team[] = $group;
}
for ($a = 0; $a < $num_teams; $a++) {
if (isset($num_array)) {
mysql_data_seek($query_array, 0 );
$search_array_over = array();
}
$id = $id_team[$a][0];
$name_over = $id_team[$a][1];
$query_array = mysql_query("select * from full_stat where kl1 = $id or kl2 = $id");
$num_array = mysql_num_rows($query_array);
while ($row = mysql_fetch_row($query_array)) {
$data_over[] = $row;
}
$search_array_over = array('1' => '0', '2' => '0' ,'3' => '0', '4' => '0','5' => '0','6' => '0');
for ($now = 0;$now < $num_array; $now++) {
$over_pass = ($data_over[$now][3] + $data_over[$now][4]);
for ($pass = 1; $pass < 7; $pass++) {
if ($over_pass >= $pass) {
$final_pass = $pass;
}
else {
$final_pass = '6';
}
if (array_key_exists($final_pass, $search_array_over)) {
$search_array_over[$final_pass] += 1;
}
else {
$search_array_over[$final_pass] = 1;
}
}
}
echo '<tr><td>'.$name_over.'</td><td>'.$num_array.'</td> <td>'.$search_array_over[1].'</td><td>'.$search_array_over[2].'</td><td>'.$search_array_over[3].'</td><td>'.$search_array_over[4].'</td><td>'.$search_array_over[5].'</td></tr>';
}
?>
</tbody>
</table>
That is one confusing block of PHP code.
A better explanation of your final output would probably help here, but I'm going to guess it's the teamlist plus their statistics.
Since dissecting your current code strikes me as painful, I'm going to describe how I would do this instead.
In your database you have 2 tables, "team" and "team_stats"
Team Structure:
id int
name varchar
....
Stats Structure:
team_id int
someStat int
otherStat int
....
$stmt = $mysqli -> prepare("SELECT * FROM team LEFT JOIN team_stats ON team_stats.team_id");
$stmt -> execute();
$result = $stmt -> fetch_all();
foreach($result as $team) {
// output data to page
}
?>

Php: loop breaks when call a method inside a while in a class

I have a problem in a class I can't solve, the loop breaks in getAlojamiento() when I call getImagenes() inside the while. In this case getAlojamiento() returns only one row, it should return all the rows. Here are the methods involved:
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY, IF $id IS SET, CHECKS IF id_asoc == $id
public function getImagenes($table, $id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM $table WHERE id_asoc = '$id' ORDER BY id DESC";
}else{
$id = '';
$sql="SELECT * FROM $table ORDER BY id DESC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return = $items;
}
}
return $return;
}
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY
public function getAlojamiento($id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM tb_alojamiento WHERE id = '$id' LIMIT 1";
}else{
$id = '';
$sql="SELECT * FROM tb_alojamiento ORDER BY titulo ASC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$imagenes_arr = $this->getImagenes('tb_alo_imagenes', $f->id); //this is causing the break
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
$items[$f->id]['telefono'] = $f->telefono;
$items[$f->id]['descripcion'] = $f->descripcion;
$items[$f->id]['email'] = $f->email;
$items[$f->id]['url'] = $f->url;
$items[$f->id]['direccion'] = $f->direccion;
$items[$f->id]['ubicacion'] = $f->ubicacion;
$items[$f->id]['coordenadas'] = $f->coordenadas;
$items[$f->id]['disponibilidad'] = $f->disponibilidad;
$items[$f->id]['tarifas'] = $f->tarifas;
$items[$f->id]['servicios'] = $f->servicios;
$items[$f->id]['theme'] = $f->theme;
$items[$f->id]['premium'] = $f->premium;
$items[$f->id]['img_ppal_id'] = $f->img_ppal_id;
$items[$f->id]['imagenes'] = $imagenes_arr;
}
$return = $items;
}
}
return $return;
}
The problem is that you are using $this->dbResults for both queries. When you call getImagenes you are clobbering the dbResults in getAlojamiento.
A simple solution to avoid having the first mysql query affect other queries is to complete it first:
//first loop over the result set from first query
while($f = mysql_fetch_object($this->dbResults))
{
//note: no call to $this->getImagenes here!
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
....
}
//only now you fetch the images in a second pass
foreach( $items as $id => $item )
{
$items[$id]['imagenes'] = $this->getImagenes('tb_alo_imagenes', $id);
}
//return the complete $items array
$return = $items;
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return[] = $items;
You're setting the array to be the single $items array. You need to add it to the $return array.

Categories