I'm using the following piece of code to count the number of locations from a table:
$result = mysqli_query($conn,"SELECT location FROM table ORDER BY location");
$aloc_list = array();
while ($row = mysqli_fetch_array($result))
{$aloc_list[] = $row['location'];
}
print_r(array_count_values($aloc_list));
Which gives me the following array:
Array
(
[CANADA] => 106
[USA] => 547
[MEXICO] => 93
[GREAT_BRITAIN] => 111
[EASTERN_EUROPE] => 227
[RUSSIA] => 405
[CHINA] => 341
[INDIA] => 253
)
I have tried to 'extract' the array values and put them in a variable but nothing seems to work:
$canada = $aloc_list[0];
$canada = $aloc_list['CANADA'];
$canada = $aloc_list[0]['CANADA'];
$canada = $aloc_list[0];
I want to end up with a variable called $canada equal to 106, a variable called $usa equal to 547, etc.
How do I accomplish this?
If you don't want to change your query, you can store the result of array_count_values($aloc_list) and use it to extract the datas. You can use variables variables to generate dynamically variables, but I don't recommend this. You might want to check if variable exists before using it. (isset())
$aloc_list_count = array_count_values($aloc_list);
var_dump($aloc_list_count);
/*
Outputs
array (size=8)
'CANADA' => int 106
'USA' => int 547
'MEXICO' => int 93
'GREAT_BRITAIN' => int 111
'EASTERN_EUROPE' => int 227
'RUSSIA' => int 405
'CHINA' => int 341
'INDIA' => int 253
*/
foreach ($aloc_list_count AS $key => $value)
${strtolower($key)} = $value;
echo $canada; //106
echo $usa; //547
echo $france; //Notice: Undefined variable: france in...
Or you can use extract function to achieve that
extract($aloc_list_count);
You are trying to select the mentioned values from the original $aloc_list array - but they don't directly exist in there. They're the result of the call to array_count_values($aloc_list) - this produces a new array, and you need to read from that instead.
For example:
$counts = array_count_values($aloc_list);
$canada = $counts['CANADA'];
echo $canada;
Instead of doing it at PHP level, you could do it in much more efficient way in MySQL itself, utilizing Count with Group By.
Also, you will need to use mysqli_fetch_assoc instead of mysqli_fetch_array, because you cant access 'location' key, without getting associative output.
Also, most important thing is that you should use Prepared Statements to avoid SQL Injection related issues!
Try the following instead:
$sql = "SELECT location, COUNT(*) as count_per_location
FROM table
GROUP BY location
ORDER BY location"
$result = mysqli_query($conn, $sql);
$aloc_list = array();
while ($row = mysqli_fetch_assoc($result))
{
${strtolower($row['location']} = $row['count_per_location'];
}
on the line with:
print_r(array_count_values($aloc_list));
Try this instead:
$mergeLocations = array_count_values($aloc_list);
var_dump($mergeLocations['CANADA']);
var_dump($mergeLocations['USA'])
By the way, would be smarter to use mysql GROUP BY function for counting locations:
SELECT location, count(*) as total FROM table GROUP BY location ORDER BY total DESC
you are returning the array from array_count_values into the print_r function. try this
$test = array_count_values($aloc_list);
echo $test['CANADA'];
Related
This question already has answers here:
MySQLi query returns only one row
(3 answers)
Closed 6 years ago.
Here, I want to print those value which are in table.
So, my query is like this:
$get_role_query = "SELECT id FROM table WHERE id IN (333,1,2)";
$roleres = mysqli_query($conn,$get_role_query);
$r_id = mysqli_fetch_assoc($roleres);
Here, 333 is not in table but 1 and 2 are in table.
When I am printing this like,
print_r($r_id);
It only gives me 1 but not getting 2 which is also in table. I don't want 333 that is fine. But I am getting only 1, not getting 2.
UPDATED BELOW:
As you all suggest to use while loop, I did like this:
$r_role = mysqli_num_rows($roleres);
for($i=0;$i<=$r_role;$i++)
{
print_r($r_id);
}
But I am getting output like this:
Array
(
[id] => 1
)
Array
(
[id] => 1
)
Array
(
[id] => 1
)
From above query, I just want output like,
Array
(
[0] => 1
[1] => 2
)
Any suggestion would be appreciated.
Thanks.
Use while in order to fetch multiple values from the table:
$get_role_query = "SELECT id FROM table WHERE id IN (333,1,2)";
$roleres = mysqli_query($conn,$get_role_query);
while($r_id = mysqli_fetch_assoc($roleres))
{
echo $r_id['id'];
}
You can also use an object method instead array method.
$get_role_query = "SELECT id FROM table WHERE id IN (333,1,2)";
if ($result = $mysqli->query($get_role_query)) {
/* fetch object array */
while ($obj = $result->fetch_object()) {
echo $obj->id;
}
}
/* free result set */
$result->close();
You are not using mysqli_fetch_assoc() correctly. It fetches one record at a time. Use it as follows:
while($r_id = mysqli_fetch_assoc($roleres))
{
print_r($r_id);
}
I'm trying to save with foreach
here is what i get from my form
Array
(
[mulai] => 2016-08-28
[akhir] => 2016-08-31
[keterangan] => remarks
[nip] => Array
(
[0] => 1004384
[1] => 1602744
[2] => 1501039
)
)
and then here is my saving query.
$jumlahrange = $this->db->query("SELECT DATEDIFF(day,'".$mulai."','".$akhir."') AS diff")->row();
$totaldata = count($nip);
$skrg = $this->db->query("SELECT GETDATE() tgl")->row();
for($x = 0;$x<=$totaldata;$x++)
{
for($y=0;$y<$jumlahrange->diff;$y++){
$this->db->query("INSERT INTO attendance
(Nip,AttendanceDate,InTime,OutTime,AttendanceCode,RosterCode,LocationCode,Remarks,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy)
values(
'".$nip[$x]."',DATEADD(DAY,".$y.",'".$mulai."'),'','','P3','','','".$keterangan."','".$skrg->tgl."','$niplogin','','')
");
}
}
i have no problem with my save but i have empty field like this in my table. In row 10,11,12 . That row should not exist right?.
I using SqlServer 2008 and Codeigniter . I know i can use insert_batch, but i want use this way.
in your line for($x = 0;$x<=$totaldata;$x++) i'm pretty sure you wanted to write < instead of <=
To overcome these kind of issues you can use foreach loop instead
foreach($resourcedata as $value){
//your code goes here and you will get all array elements sequentially in **$value** variable
}
This one is right at your fingertips. $nip[$x] is null. Error log or dump and die on the first loop $nip[$x] and see what it returns. If it is in fact not null, then it might be a data type problem (string vs int).
I am trying to search one word in my whole table.
So if you search Eminem, you have to get everything with the word Eminem.
I search
<?php
$sql="SELECT * FROM album WHERE albumartiest like '$zoek'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumnaam like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumartiest like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumgenre like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
$sql="select * from album where albumafspeelijst like '%$zoek%'";
$resultaatcolumn = Yii::app()->db->CreateCommand($sql)->queryAll();
if($resultaatcolumn != null){
$zoekresultaat[] = $resultaatcolumn;}
It works, but not exactly how I want it.
The result is this:
Array ( [0] => Array ( [0] => Array ( [albumcode] => 45 [albumnaam] => recovery [albumafspeelijst] => ["Cold Wind Blows","Talkin' 2 Myself","On Fire","Won't Back Down","W.T.P.","Going Through Changes","Not Afraid","Seduction","No Love","Space Bound","Cinderella Man","To Life","So Bad","Almost Famous","Love The Way You Lie","You're Never Over",""] [albumartiest] => Eminem [albumgenre] => hip-hop [albumimage] => images\eminemrecovery.png [albumprijs] => 20 ) ) [1] => Array ( [0] => Array ( [albumcode] => 45 [albumnaam] => recovery [albumafspeelijst] => ["Cold Wind Blows","Talkin' 2 Myself","On Fire","Won't Back Down","W.T.P.","Going Through Changes","Not Afraid","Seduction","No Love","Space Bound","Cinderella Man","To Life","So Bad","Almost Famous","Love The Way You Lie","You're Never Over",""] [albumartiest] => Eminem [albumgenre] => hip-hop [albumimage] => images\eminemrecovery.png [albumprijs] => 20 ) ) )
that's okay, but what I want is take out variable's and use it.
is there a way that I can get variable's out of the array and use it?
If you guys want more information about my code please ask!
Try using this
Yii::app()->db->CreateCommand($sql)->setFetchMode(PDO::FETCH_OBJ)->queryAll()
This will give you an array of objects with column name as the properties.
Eg:-
foreach($result as $row)
{
echo $row->albumcode;
}
If you want to access the result set like an object you can use the native PHP class ArrayObject and provide the flag to indicate that.
$album = new ArrayObject($result, ArrayObject::ARRAY_AS_PROPS);
You can now access the results like the following:
$code = $album->albumcode;
$name = $album->albumnaam;
Hope this can guide you, happy coding!
uhhh just do
foreach($zoekresultaat as $key => $value) {
//do what I want with each seperate returened result. The array key is in $key and the result array is in $value
echo $value['albumcode'] . ' = '. $value['albumnaam'];
}
aka, basic php
And please for the security of your app, learn how to do prepared statements in yii
The way your query is now I could wipe your entire database
I have a MySQL query using Laravel that I convert to a PHP Array.
The rows have values similar to this:
name | override | percentage
Eclipse | 1 | 50%
Eclipse | 0 | 75%
MySQL query
select * from table
Both rows (it's many more than just 2 in reality) have the same name, but one has override set to 0 and one has it set to 1.
How can I get rid of all records in my query result (PHP array) that are duplicates (determined by the name) AND have override set to 0? I want only the records that have been overridden with a new record which I have done, but I need a way to remove the records with override = 0, given that the records are the same but have a different percentage value.
How can this be done?
Thanks.
Try following query,
SELECT * from testtable GROUP BY `name` HAVING count(`name`) = 1 OR `override` = 1;
check this sqlfiddle
If I understand your needs correctly, you need to filter out records that have duplicate name and override = 0.
If you sort your result set by name (SELECT * FROM TABLE ORDER BY name), you can use this function.
function removeDuplicatesFromArray($rows) {
$result = array();
$old_name = '';
foreach($rows as $row) {
if($row['name'] != $old_name) {
$result[] = $row;
$old_name = $row['name'];
}
elseif($row['override'] == 1) {
array_pop($result);
$result[] = $row;
}
}
return $result;
}
NOTE: Doing this in SQL will be WAYYYYYYYYY faster and use far less memory. I would only try this PHP approach if you cannot modify the SQL for some reason.
Maybe try out... hit the db twice, first time only get non-overrides, then get the overrides in second pass -- coerce your arrays to be indexed by name and array_merge them. (Uses a fair chunk of memory given the number of arrays and copies - but it's easy to understand and keeps it simple.
$initial = get_non_overridden();
$override = get_overridden();
$init_indexed = index_by_name($initial);
$over_indexed = index_by_name($override);
$desired_result = array_merge($init_indexed, $over_indexed);
Assuming your database gives you a standard rowset (array of rows, where each row is a hash of fields->values). We want something that looks like this instead:
[
'Eclipse' => [
'name' => 'Eclipse',
'override' => '0',
'percentage' => '75%'
],
'Something' => [
'name' => 'Something',
'override' => '0',
'percentage' => '20%'
],
]
So index_by_name would be:
function index_by_name($rowset) {
$result = array();
foreach ($rowset as $row) {
$result[ $row['name'] ] = $row;
}
return $result;
}
There are ways to tweak your efficiency either in memory or run time, but that's the gist of what I was thinking.
array_merge then overwrites the initial ones with the overridden ones.
NOTE: this all assumes that there is only one row where Eclipse override is 1. If you have twenty Eclipse|0 and one Eclipse|1, this will work, if you have two Eclipse|1 you'd only see one of them... and there's no way to say which one.
Hey guys i want to use two arrays in on mysql UPDATE query. So here is what i have:
For example:
$ergebnis:
Array ( [0] => 100 [1] => 200 [2] => 15 )
$Index:
Array ( [0] => 3 [1] => 8 [2] => 11 )
And this is what i tried:
UPDATE `lm_Artikel`
SET Bestand='".$ergebnis."'
WHERE `Index` = '".$Index."'
This query seems not to work. I don't know why i enabled php error reporting and there are no errors and when i run the query it doesn't change anything in my database. Can anyone see what i did wrong?
You need to do it for each element of your arrays, hence, you can use the foreach() function:
foreach($ergebnis as $key => $value){
$sql = "UPDATE lm_Artikel SET Bestand='".$value."' WHERE `Index` = '".$Index[$key]."'";
mysqli_query($sql);
}
P.S. There could well be a pure-sql alternative but I'm not too SQL-hot, so I'll leave it to someone who has more expertise.
Also, please note that it may be easier for you to set the index as the array keys:
$ergebnis = Array(3=>100, 8=>200, 11=>15);
And then the foreach() would look a little better:
foreach($ergebnis as $key => $value){
$sql = "UPDATE lm_Artikel SET Bestand='".$value."' WHERE `Index` = '".$key."'";
mysqli_query($sql);
}
Fellow,
it looks like that your database field is an int value so you can try doing it value by value, like this:
foreach( $Index as $key => $i ) :
$query = "UPDATE lm_Artikel SET Bestand=".$ergebnis[$key]." WHERE Index = " . $i;
mysqli_query($query);
endforeach;
Try it.
You are susceptible to SQL injections
You cannot use arrays in queries. A query is a string, arrays are not.
You either need to use a loop or use a CASE statement:
UPDATE `lm_Artikel`
SET `Bestandteil` = CASE `Index`
WHEN <insert id> THEN <insert value>
WHEN <insert other id> THEN <insert other value>
<etc>
END
$data_db = array( '3' => 100,
'8' => 200,
'11' => 15);
foreach($data_db as $key=>$value) {
$q = 'UPDATE lm_Artikel SET Bestand=' . $value . ' WHERE `Index` = ' . $key;
mysqli_query($sql);
}
Assuming these are value pairs, i.e. $ergebnis[0] is for $Index[0] and so forth.
foreach ($ergebnis as $key => $value) {
$sql = 'UPDATE lm_Artikel SET Bestand=' . (int)$value . ' WHERE `Index` = ' . (int)$Index[$key];
// execute query...
}
A few notes:
You are open to SQL Injection. I used (int) as a quick patch.
I would encourage you to look into Prepared Statements.
You should avoid naming your columns SQL keywords, e.g. Index.