update record from array - php

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!

Related

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>

create ad multidimensional array and display it with a foreach loop

I've a problem with php and foreach...
The first query result like this:
while ($row = $s->fetch())
{
$registration[] = array(
'id_registration' => $row['id_registration'],
'discipline' => $row['discipline'],
'speciality' => $row['speciality'],
'category' => $row['category'],
'subcat' => $row['subcat']
);
}
excuse me, I was not very precise...
I have 2 table
- the first has a primary key (id_registration) that identifies the registration
- in the second table there are firstrname and lastname of the athletes which refer to the first table by id_registration.
how can I get all the registrations and the athletes of every registration and print all with one o more foreach loop?
I hope I was clear.
$iscrizioni = array();
while ($row = $s->fetch())
{
$iscrizioni['id_gara'] = $row['id_gara'];
$iscrizioni['disc'] = $row['disc'];
$iscrizioni['spec'] = $row['spec'];
$iscrizioni['cat'] = $row['cat'];
$iscrizioni['subcat'] = $row['subcat'];
}
pre($iscrizioni);

array not working mysql 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']; }

Create Array and print it into TXT file

UPDATE:
I get array values from $_POST['changed'].
The array structure looks like this:
Array
(
[0] => Array
(
[recid] => 1
[nachname] => Müller7777
)
[1] => Array
(
[recid] => 3
[vorname] => Maria123
)
)
I get on line #3 this error: Fatal error: Function name must be a string
$uarr=array();
foreach ($_POST['changed'] as $a) {
list($x,$k)=array_keys($a);
list($y,$v)=array_values($a);
$uarr[$y][]="$k='$v'";
}
foreach ($uarr as $k=>$v) {
$sql = "";
$sql .="UPDATE tbl SET ".join(",",$v)." WHERE recid=$k";
// send UPDATE ...
}
file_put_contents('filename2.txt', $sql);
Before I do the final database UPDATE I want to check if the created array does its job. Thats why I want to write the $sql variable first into a txt-file.
------------------------------------------------
SOLUTION:
checking if $_POST['changed'] == null is the final answer for this question.
if ($_POST['changed'] == null) {
} else {
$uarr=array();
$b = $_POST['changed'];
foreach ($b as $a) {
list($x,$k)=array_keys($a);
list($y,$v)=array_values($a);
// $x contains the `recid` key
// $y ... value
$uarr[$y][]="$k='$v'";
}
foreach ($uarr as $k=>$v) {
$sql = "";
$sql .="UPDATE tbl SET ".join(",",$v)." WHERE recid=$k";
// send UPDATE ...
}
file_put_contents('filename2.txt', $sql);
}
Before you run the individual UPDATE statements - yes, for each recid value you should send one statement - you could first collect all the affected values for each recid in an associative array like
$uarr=array();
foreach ($_POST['changed'] as $a) {
list($x,$k)=array_keys($a);
list($y,$v)=array_values($a);
// $x contains the `recid` key
// $y ... value
$uarr[$y][]="$k='$v'";
}
and then do another loop like
foreach ($uarr as $k=>$v) {
$sql="UPDATE tbl SET ".join(",",$v)." WHERE recid=$k";
// send UPDATE ...
}
But, of course, this will only work correctly if the $_POST('changed') array adheres to the described format and order. And, finally, so far there is nothing in this code to protect you from SQL injection.
Try to do it like this:
$BigArray = $_POST['changed'];
$LengthOfArray = sizeof($BigArray);
for ($i = 0; $i < $LengthOfArray ; $i++) {
$SubArray = $BigArray[$i];
// Call the update/insert here
// $SubArray['recid'] is the ID
// $SubArray['vorname'] is the name
}

Looping through post data and updating corresponding database records

I am trying to loop through some data I post through jQuery. Here is my PHP script:
<?php
include '../dbconnect.php';
$map = $_POST['map'];
$position = 0;
foreach ($map as $ID)
{
if ($_POST['type'] == "sub") {
$query = "UPDATE Subcategories SET `Position` = '$position' WHERE CategoryID = '$ID';";
} else {
$query = "UPDATE Categories SET `Position` = '$position' WHERE CategoryID = '$ID';";
}
$result = mysql_query($query) or die(mysql_error());
$position ++;
}
?>
and the data it is recieving as $map is sent in this format:
ID[]=27&ID[]=28&ID[]=33&ID[]=19
Obviously my foreach is wrong, but how would I go about getting it so that I retain $maps order and each numerical value becomes the variable $ID?
Ok, Since your $map contains, ID[]=27&ID[]=28&ID[]=33&ID[]=19 string value. Do something like this
$str = str_replace($map, "ID[]=","");
$mArr = explode("&", $str);
foreach($mArr as $key) {
//now your $key will have 27, 28, 33, 19 as the loop progresses
}
P.S. Based on the OP's comment of $map having a string output of that
Can you show us what print_r($map); displays.
If it's just a string in the format you've described, I'd suggest changing the format of map to something easier to loop through like json. For example
{"map":[27,28,33,19]}
Then you can use
<?php
$mapObject = json_decode($_POST['map']);
$mapArray = $mapObject->map;
foreach($mapArray as $id)
{
echo $id;
}
?>
You can POST it without the map, just
$.ajax({ type: 'POST', url: 'updatecategoryposition.php', data: map + "&type=sub" });
I'm assuming that map contains 'ID[]=27&ID[]=28&ID[]=33&ID[]=19'
As an alternative you can save the map in a different format so you end up with map being just a list of IDs ($map="27,28,33,19"), use the original jquery post and finally use
$map = explode(',' $_POST['map']);
I'm not entirely sure, but is this what you meant? It works, if I understand your problem correctly.
<?php
include '../dbconnect.php';
$position = 0;
$pattern = '/ID\\[\\]=(\d+)&*/';
$subject = $_POST['map'];
preg_match_all($pattern, $subject, $matches);
foreach ($matches as $k => $ID) {
// etc
Test Case
Try this test, in a separate script. The output from $matches[1] are what you would feed to the foreach loop if you used this script. Does this retrieve what you want?
<?php
$pattern = '/ID\\[\\]=(\d+)&*/';
$subject = 'ID[]=27&ID[]=28&ID[]=33&ID[]=19';
preg_match_all($pattern, $subject, $matches);
echo '<pre>'.print_r($matches,1).'</pre>';
?>
Outputs:
Array
(
[0] => Array
(
[0] => ID[]=27&
[1] => ID[]=28&
[2] => ID[]=33&
[3] => ID[]=19
)
[1] => Array
(
[0] => 27
[1] => 28
[2] => 33
[3] => 19
)
)
Thanks for trying guys, but in the end I couldn't get any suggestions to work but I did find a solution:
Update category position:
<?php
include '../dbconnect.php';
foreach ($_POST['ID'] as $position => $ID){
$query = "UPDATE Subcategories SET `Position` = '$position' WHERE CategoryID = '$ID';";
$result = mysql_query($query) or die(mysql_error());
}
?>
and the new Jquery post request courtesy of Starx (telling me to remove variable name), as a result I can access the query string as above:
$.ajax({
type: 'POST',
url: 'updatecategoryposition.php',
data: map
});

Categories