I have an array that is populated by a mysql_fetch_assoc. After the array is populated by the columns I want from the database, I would like to add another key to the array, using values that I obtain earlier in the function. I tried to accomplish this with a foreach loop, but my function is not returning the array. Where have I gone wrong?
//calculates payout
function calculate_payout($id){
$result = mysql_query("SELECT `result` FROM `bets` WHERE `id` = {$id}");
echo mysql_error();
$wager_total = mysql_query("SELECT SUM(`wager_amount`) AS `wager_total` FROM `wagers` WHERE `id` = '{$id}'");
$correct_wager_total = mysql_query("SELECT SUM(`wager_amount`) AS `correct_wager_total` FROM `wagers` WHERE `id` = '{$id}' AND `wager_option` = '{$result}'");
echo mysql_error();
$incorrect_wager_total = $wager_total - $correct_wager_total;
$sql = " SELECT * FROM `wagers` WHERE `id` = '{$id}' AND `wager_option` = '{$result}'";
echo mysql_error();
$data = mysql_query($sql);
$rows = array();
while(($row = mysql_fetch_assoc($data)) !== false){
$rows[] = array(
'bet_id' => $row['bet_id'],
'id' => $row['id'],
'wager_amount' => $row['wager_amount']
);
}
foreach ($rows as $p_row){
$payout = $p_row['wager_amount'] / $incorrect_wager_total;
$payout = $p_row['wager_amount'] + $payout;
$p_row['payout'] = $payout;
}
return $p_row;
}
The problem is that $p_row is a copy of the row in the array, so modifying it in the loop doesn't have any effect on the original array.
You can fix this by using a reference in the foreach:
foreach ($rows as &$p_row)
Or you can just do this as you're creating the $rows array in the while loop:
while ($row = mysql_fetch_assoc($data)) {
$new_row = array(
'bet_id' => $row['id'],
'id' => $row['id'],
'wager_amount' => $row['wager_amount'],
'payout' => $row['wager_amount'] / $incorrect_wager_total + $row['wager_amount']
);
Also, your return statement is wrong, it should be return $rows; to return the whole array; return $p_row will just return the last row of the array.
Related
I am new to PHP. I am trying to read MySQL with this PHP code.
....
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$rows = array();
$return = array();
while($row = mysqli_fetch_array($result)) {
$rows['UserId'] = $row['UserId'];
$rows['Nick'] = $row['Nick'];
$rows['Items'] = $row['Items'];
$rows['Skills'] = $row['Skills'];
...
$rows['LastUpdate'] = $row['LastUpdate'];
array_push($return, $rows);
}
header("Content-type:application/json");
echo json_encode($return);
Soon after runnning this code, it gets into infinite loop.
When I deleted the array_push line, it did not go into infinite loop.
So I guess that'd be the problem, but I can't find out why.
Is there something wrong with my code?
The MySQL database is in Amazon lightsail.
Please help me. Thanks in advance for any comments.
if you want to fetch all rows from database, and get data array of specific fields
<?php
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$filtered = [];
while($row = mysqli_fetch_all($result)) {
$filtered[] = [
'UserId' => $row['UserId'],
'Nick' => $row['Nick'],
'Items' => $row['Items'],
'Items' => $row['Items'],
'Skills' => $row['Skills'],
'Items' => $row['Items'],
'LastUpdate' => $row['LastUpdate'],
];
}
header("Content-type:application/json");
echo json_encode($filtered);
foreach record of your database information you are entering new data to rows array
while($row = mysqli_fetch_array($result)) {
// Logic of you application here
array_push($return, $row);
}
this pushes fetched row into rows array
how ever if you are not modifying database fetched information. you can fetch information as associative array and simply store it in variable. there will be no need for loop and storing in new array
$sql = "select * from GameMaster where UserId = '".$_POST["UserId"]."'";
$result = mysqli_query($link, $sql);
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
header("Content-type:application/json");
echo json_encode($rows);
I want to implement GROUP BY clause of SQL using Yii. Here I faced problem of returning only first row instead of all rows.
$connection = Yii::app()->db;
$sql = "SELECT group_name FROM `authitem` GROUP BY group_name";
$command = $connection->createCommand($sql);
$row = $command->queryRow();
print_r($row);
$res = array();
foreach ($row as $key => $val) {
$res[] = array('label' => $key, 'value' => $val);
}
print_r($res);
instead of
$row = $command->queryRow();
try like this,
$row = $command->queryAll();
MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}
I have this piece of code:
Tipo_Id = mysql_real_escape_string($_REQUEST["tipo"]);
$Sql = "SELECT DISTINCT(tabveiculos.Marca_Id), tabmarcas.Marca_Nome
FROM tabmarcas, tabveiculos
WHERE tabmarcas.Tipo_Id = '$Tipo_Id'
AND tabmarcas.Marca_Id = tabveiculos.Marca_Id
ORDER BY tabmarcas.Marca_Nome Asc";
$Query = mysql_query($Sql,$Conn) or die(mysql_error($Conn));
$marcas = array();
while ($Rs = mysql_fetch_array($Query)) {
$marcas[] = array(
$Rs['Marca_Id'] =>
$Rs['Marca_Nome']
);
}
echo ( json_encode($marcas) );
this returns a result like this:
[{"2":"Chevrolet"},{"7":"Citro"},{"4":"Fiat"},{"3":"Ford"},{"6":"Peugeot"},{"1":"Volkswagen"}]
so how i can change to returns like this:
{"2":"Chevrolet","7":"Citro","4":"Fiat","3":"Ford","6":"Peugeot","1":"Volkswagen"}
You're currently creating a new array for each key value pair, hence, ending up with a multidimensional array. Do the following instead.
while ($Rs = mysql_fetch_array($Query)) {
$marcas[ $Rs['Marca_Id'] ] = $Rs['Marca_Nome'];
}
I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function