I have this PHP syntax and works as I expected :
$sqldata = mysql_query("
SELECT FirstName, LastName, NumberOfChildren, SchoolTuition FROM User WHERE User.Username = '$Username' LIMIT 1;
");
$rows = array();
while($r = mysql_fetch_assoc($sqldata)) {
$rows[] = $r;
}
echo json_encode($rows);
now, the problem is I want to calculate total school tuition (NumberOfChildren * SchoolTuition) and it must be done before json_encode() function. and my client doesn't want to add one extra column on their database.
so I must calculate this TOTAL School Tuition using PHP and put it back on $rows array as latest value of array before json_encode.
I tried calculate using mysql_fetch_array first to get $rows[2] and $rows[3], but since I already use mysql_fetch_assoc before, this mysql_fetch_array won't work.
last thing, I mysql_fetch_assoc generates 2 dimensional array. because when I use print_r($rows), I see this :
Array ( [0] => Array ( [FirstName] => Mary [LastName] => Smith [NumberOfChildren] => 3 [SchoolTuition] => 2000 ) )
while array_push function only used to push 1 dimensional array, right?
please kindly give me solution of this problem. thank you very much.
You can just do the calculation in SQL, without having to add the column.
SELECT FirstName, LastName, NumberOfChildren, SchoolTuition,
(NumberOfChildren * SchoolTuiton) AS TotalSchoolTuiton
FROM User WHERE User.Username = '$Username' LIMIT 1
SELECT FirstName, LastName, NumberOfChildren, SchoolTuition, NumberOfChildren*SchoolTuition AS TotalTuition FROM User WHERE User.Username = '$Username' LIMIT 1;
Related
Good mornin'.
I've been tryin to make "something" that will compare matchup percentage but i'm stuck'd at searching for matches with 2 same players.
I've found something about AND OR parenthesis so here is my sql query
$ccc = "SELECT * FROM zapasy WHERE (playerName01 = '".$player1."' OR playerName01 ='".$player2."') AND (playerName02 = '".$player2."' OR playerName02='".$player1."')";
$result3 = $db->query($ccc);
$ids = array();
while ($row55 = $result3->fetch_assoc())
{
$ids[] = $row55['winner'];
}
But , the problem is whenever i try to get data , it gives me more indexes than actualy expected.
This is the result of printing array values after fetching.
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 )
As expected is only 2 3 4 as u can see in the DB sample here.
db sample
Anyone suggestions on what i'm doing wrong?
A simple way to write this in MySQL uses tuples:
where (?, ?) in ( (playername01, playername02), (playername02, playername01) )
The ? are for parameters. That should be the way that you pass values into queries.
You are doing wrong while using AND OR in where clause
$ccc = "SELECT * FROM zapasy WHERE (playerName01 = '".$player1."' AND playerName02 ='".$player2."') OR (playerName01 = '".$player2."' AND playerName02='".$player1."')";
Try this #Patrik Dano
I have 2 MySql queries which are interdependent.
My 'table1'
----------
id
----------
1
2
3
4
5
6
7
My First query
$sql1 = "SELECT * FROM table1 WHERE";// some condition which gives me id's 1,2,3
$res1=$obj->_executeQuery($sql1);
$res1=$obj->getAll($res1);
The result of this is giving me array
Array
(
[0] => Array
(
[id] => 1
..
..
)
[1] => Array
(
[id] => 2
..
..
)
[2] => Array
(
[id] => 3
..
..
)
)
I want to run another query on same 'table1', where not equal to list of ID's which i am getting from the first query.
My Second Query
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (" . implode(',', $res1) . ")";
This is not showing me only one id i,e first. In above case i should get id's 4,5,6,7
Since implode will not give the desired value on multidimensional array so first you need to get the array of all id's to form one-dimensional array then use implode on the array of id's:
$id=array();
foreach ($res1 as $key=>$inner_array){
$id[]= $inner_array['id'];
}
you can use array_walk also here like this:
array_walk($res1,function($c) use (&$id) {$id[] = $c['id'];});
but i think the best one is array_map :
$id = array_map(function($i) {
return $i['id'];
}, $res1);
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (" . implode(',', $id) . ")";
Note: when ever you are doing select please specify your column if you need few to select,unnecessarily selecting all will slow your sql processing.
suppose here:SELECT * FROM table1 WHERE, if you need only id then please select id only.
You have to change $res1, which is a two-dimensional array, into a one-dimensional array of IDs to be able to use implode:
$ids_from_first_query = array();
foreach($res1 as $result_row) {
$ids_from_first_query[] = $result_row['id'];
}
$ids_as_string = implode(',', $ids_from_first_query);
$sql2 = 'SELECT * FROM table1 WHERE id NOT IN(' . $ids_as_string . ')';
In the above code, $ids_as_string will look like this:
1,2,3
Thus it can be used in your MySQL query
Here you are getting two dimensional array so that's reason it is not working
while($each=mysql_fetch_array($res1))
{
$array[]=$each[id];
}
$imp=implode(",",$array);
$sql2 = "SELECT * FROM table1 WHERE id NOT IN (".$imp.")";
Try this it will works
I am having trouble trying to figure out how to populate a multi-dimensional array. Let's say I have a table of transactions with various billing dates. First I have an array that retrieves the following 'billed' dates:
Array
(
[0] => Array
(
[BILLED] => 2011-11-18 00:00:00
)
[1] => Array
(
[BILLED] => 2011-11-22 00:00:00
)
)
I also have the following query which is currently hard-coded to one of the two 'billed' dates shown above:
$qryOrders = $this->db->query("
SELECT tblOrders.*
FROM tblOrders
WHERE tbltc.BILLED = '2011-11-22'");
$data['Orders'] = $qryOrders->result_array();
I know that I can very easily determine the count of array items by using count($Orders); but how can I instead pass through each of the 'billed' dates of 2011-11-18 and 2011-11-22 to that I can determine the overall count, for both of the specified dates?
I hope I've explained it clearly enough. I am thinking that I probably need some kind of foreach loop and each time through the loop I could pass in the billed date, and keep track of a running total each time through the loop.
Any ideas would be greatly appreciated. Thanks,
// this is getting all results for a record
$sql =
<<<sql
SELECT tblOrders.*
FROM tblOrders
WHERE tbltc.BILLED between '{$arr[0]}' and '{$arr[1]}'
sql;
// this is to get total count of matched record
// $sql = 'select count(*) from ..';
if you are using CI, you can easily using bind
example:-
$sql = 'SELECT tblOrders.* FROM tblOrders WHERE tbltc.BILLED between ? AND ?';
$this->db->query($sql, array($arr[0], $arr[1]));
Below is code which I want to use to delete messages. I need not only to delete messages but also update total number of messages in "pmessages_folders" table.
Let's say, I want to delete messages with ids 3,4,5. Two of these messages are in the same folder:
message 3 -> folder 1
message 4 -> folder 2
message 5 - > folder 2
So, from folder 2 will be deleted 2 messages and I need to set total_messages for this folder -2 but query (result2) updates it only once. Itlooks that array_push ignores identical values.
Is there any way how to solve this problem?
Thanks.
$result = mysql_query("SELECT sender FROM messages
WHERE id IN(". implode(', ', $_POST['msg_id']).")") or die ('Error1');
$memberids = array();
while ($row = mysql_fetch_assoc($result)) {
array_push($memberids, $row['sender']);
}
$result2 = mysql_query("update messages_folders set total_messages=total_messages-1
where sender IN (".implode(",", $memberids).") and recipient='$id'") or die('Error2');
$result3 = mysql_query("DELETE FROM messages
WHERE id IN (". implode(', ', $_POST['msg_id']).")")or die('Error3');
PART 2
Here are my changes:
$result = mysql_query("SELECT sender, COUNT(sender) FROM messages
WHERE id IN(". implode(', ', $_POST['msg_id']).") GROUP BY sender") or die ('Error');
while ($row = mysql_fetch_assoc($result)) {
$memberid = $row['sender'];
$number_to_delete = $row['COUNT(sender)'];
$my_array[] = array($memberid,$number_to_delete);
}
The result:
Array
(
[0] => Array
(
[0] => 893
[1] => 1
)
[1] => Array
(
[0] => 557
[1] => 3
)
)
So, $my_array[0] contains folder ID and $my_array[1] contains number of deleted messages.
Folder 893 should be updated: total_messages= total_messages-1
and
folder 557 should be updated: total_messages= total_messages-3
No idea how to do this with IMPLODE. I need something like this:
$result9 = mysql_query("update messages_folders set total_messages=total_messages-$my_array[1]
where sender $my_array[0] and recipient='$id'") or die('Error');
I am not running this query. It's just to show what I want to achieve.
The way you are currently doing it leads to a race condition if two people simultanously try and delete the same messages, the count could go off.
It is better to delete the messages, and then update the total to be equal to the count of the messages. I would need to see the structure of your tables in order to offer an example query
Instead of array_push(), use $memberids []= $row['sender'];
This is actually recommended by php.net: http://php.net/manual/en/function.array-push.php as it is equivalent and doesn't have the function overhead. Although array_push() shouldn't care about previous values.
This is my function where i fetch my results from database
function Prof_Viewer($MemberId)
{
$query = $this->db->query("SELECT distinct(t1.dProfileId) as prof
FROM tbl_profile_viewer as t1
JOIN tbl_login as t2
WHERE t1.dProfileViwerId='$MemberId'");
if($query->num_rows > 0)
{
foreach($query->result() as $row)
{
echo $row->prof;//i am receiving many values here
$query1 = $this->db->query("SELECT distinct(t3.dUser_name),t2.dPath,t3.dCreatedDate
FROM tbl_login as t3
JOIN tbl_profile_viewer as t1,
tbl_member_details as t2
WHERE t3.dMember_Id = '$row->prof'
AND t2.dMember_Id ='$row->prof'");
}
return $query1->result_array();
}
}
As commented above i receive many values while echo the variable $row->prof;
say i have values such as 1 2 and 3.......
Even if i have these three values my 'query1' takes only the last value .so i have only one result i want the query to be executed for 1 and 2 also
how to Achieve that
You can just use PHP's explode() to convert your string into an array. For example:
<?php
$str = 'one|two|three|four';
// positive limit
print_r(explode('|', $str));
// gives you an array:
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
)
?>
But I think you would be better off if you learned how to do JOIN's:
http://en.wikipedia.org/wiki/Join_(SQL)
I'm assuming you're using mysqli here.
Result_fetch_array() will do what you want
http://au2.php.net/manual/en/mysqli-result.fetch-array.php