array not working mysql php - php

I am trying to create an array from an mysql query,
It gets around 300 values from the database yet only the first value is stored in the array. when I echo the array it says: Array ( [0] => 0.99 ). What I'm trying to archieve is
Array ( [0] => 0.99 )
Array ( [1] => 0.25 )
etc.
$activering = mysql_query("SELECT tarieven.id, bundels.bundel_id, betaalmethodes.bet_id , bundels.psp_id, bundels.aanmeldkosten, bundels.maandelijkse_kosten, bundels.transactiekosten, bundels.batchkosten, psp.psp_naam, tarieven.percentage, tarieven.prijs, bundels.actief
FROM tarieven
INNER JOIN bundels
ON tarieven.bundel_id = bundels.bundel_id
INNER JOIN betaalmethodes
ON tarieven.bet_id = betaalmethodes.bet_id
INNER JOIN psp
ON bundels.psp_id = psp.psp_id");
if($activering === FALSE) { die(mysql_error()); } // to do better error handling
if ($result = mysql_fetch_array($activering)) {
$prijs = array($result['prijs']); }
It's probably something really easy but I just don't see it..

Try
while ($result = mysql_fetch_array($activering)) {
$prijs[] = array($result['prijs']);
}

your over writing the value(array) in hte loop so you only get the last one:
$prijs[] =$result['prijs']; }

Related

Mysql returned Array with Keys and Tabelle-Names - delete Keys

I have a MySQL table, where I run a query with left join:
$db = $db->first("SELECT * FROM devices LEFT JOIN customer ON devices.customerid = customer.customerid WHERE devices.hash = '".$hash."' OR devices.deviceid = '".$hash."'");
With this function:
//Select Datenbankanfrage, erste Zeile
function first($query, $restype=0) {
$this->querystring = $query;
if ( $restype==1 ) $restype=MYSQLI_ASSOC;
else $restype=MYSQLI_BOTH;
$result = $this->query($query); //Query
if ( !$result ) return false;
$row = $result->fetch_array($restype);
$result->free();
return $row;
}
But I recieve an array with keys as response:
1 => Maxii
Name => Maxii
2 => Streetfromthe
Street => Streetfromthe
How can I disable the keys (1,2) or how can I delete this in the array?
Here is a Nopaste from the full array returned:
https://nopaste.xyz/?23ccf318bbfc93fb#Oes85/9Z8+Kookk2nTLmbtObjaL8mD2aitPPrHV3v9w=
The problem comes from $restype, your second argument. It is zero by default which would use MYSQLI_BOTH, which returns fields by both index and names. You certainly want an associative array (MYSQLI_ASSOC), passing $restype to 1.
The lines that are responsible for changing the restype are:
if ( $restype==1 ) $restype=MYSQLI_ASSOC;
else $restype=MYSQLI_BOTH;
You need to replace with $result->fetch_array with $result->fetch_assoc
EDIT: In your case, leave it at fetch_array and use the function you have.
Invoke it with first($sql, 1);

How to add <hr> tags between unique rows from query resultset?

I'm trying to add an <hr> tag between lines when a new name is encountered.
$conn = new mysqli("localhost", "root", "", "test");
$rs = $conn->query("SELECT * FROM usuarios");
$info = [];
$i = 0;
while($rows = $rs->fetch_array()) {
$info[$i]["pass"] = $rows["pass"];
$info[$i]["name"] = $rows["name_real"];
$i++;
}
// I want to print a line just after the last duplicated value
for($i = 0; $i < count($info) - 1; $i++) {
if($info[$i]["name"] !== $info[$i +1]["name"] && // some duplicate condition) {
$info[$i]["line"] = "<hr>";
};
}
This is the structure of my info array build from the resultset.
Array
(
[0] => Array
(
[pass] => 12
[name] => Martin
)
[1] => Array
(
[pass] => 20
[name] => Martin
)
[2] => Array
(
[pass] => 2
[name] => Martin
)
[3] => Array
(
[pass] => 2
[name] => Alberto
)
)
My desired result would be something like:
<p>Martin<p>
<p>Martin<p>
<p>Martin<p>
<hr>
<p>Alberto<p>
If you don't care what the duplicate names are or how many duplicates exist, and you just want to see whether or not there are any, it looks like it could be simpler code than some of the possible duplicate answers.
Get the names
$names = array_column($array, 'name');
Then check if the full list of names is equal to the unique list.
$has_duplicates = $names != array_unique($names);
Disclaimer: This answer looks odd now. It was provided for Revision 1 of the question. I seem to have misunderstood the question somewhat, and then Revision 2 transformed it to the extent that this answer no longer applies at all. Still, I think it's a useful way to do the thing that it seemed was trying to be done at first.
This solution would be handy:
$result = array();
$names = array_count_values(array_column($source, 'name'));
foreach($names as $key=>$val) {
$result[$key] = ($val == 1 ? false : true);
}
This can be achieved with just one loop. First, use your mysqli query to order the resultset by name_real. (If you are only going to use name_real, you can change the SELECT clause to reflect this. I have shown this in the commented query.) Then write a condition that checks for a new/unique name_real -- if so, echo <hr>.
Code: (Demo)
//$rs = $conn->query("SELECT `name_real` FROM usuarios ORDER BY `name_real`;");
$rs=[
['pass'=>2,'name_real'=>'Alberto'],
['pass'=>12,'name_real'=>'Martin'],
['pass'=>20,'name_real'=>'Martin'],
['pass'=>2,'name_real'=>'Martin']
];
$prev=NULL;
//while($rows = $rs->fetch_array()) {
foreach($rs as $rows){
if($prev && $rows['name_real']!=$prev){ // if not first iteration, and new name_real
echo "<hr>";
}
echo "<p>{$rows['name_real']}</p>";
$prev=$rows['name_real']; // preserve this value for next iteration's check
}
Output:
<p>Alberto</p>
<hr>
<p>Martin</p>
<p>Martin</p>
<p>Martin</p>

why i have NULL when saving data in database

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).

make an object out of an array PHP

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

update record from array

I am having an issue with updating records from an array. When I go to update I am only getting the first digit. For example if the real value is 58 I am only getting the 5 inserted
Below is my code with further explanation below:
$bidArr = $tmpArr;
foreach($tmpArr as $key => $val)
{
$sqlEp = "select sum(endpoints_c), account_id1_c as id from accounts_cstm as ac join accounts as a on a.id = ac.id_c
where account_id1_c ='$val' and (status_c IN ('active','llp')) and deleted='0'";
$rowEp = $db->query($sqlEp);
$recordEp = $db->fetch_row($rowEp);
$bidArr[$key]['sold_ep_c'] = $recordEp[0];
//print "<pre>EP";
//print_r($recordEp);
}
foreach($bidArr as $key => $val)
{
$data['sold_ep_c'] = $val['sold_ep_c'];
$db->query_update(TABLE_ACC, $data, "id_c='".$key."'");
print "<pre>EP";
print_r($key);
print_r($data);
}
What is happening is when I uncomment the first print_r I get:
EPArray
(
[0] => 16
[1] => 51067d38
which is right. But if I comment it out and uncomment the second one I get:
51067d38
(
[sold_ep_c] => 1
)
Why is this stripping the first digit?
As per chat...your arrays aren't initialized.
$bidArr[$key] = array(); in the first loop!

Categories