PHP Add ID and String into Array, in a loop - php

I need to add a UNIQUE ID and a string that is with that ID , into an array. This array needs to be updated too. Example:
ID NAME[(3,Flor)(5,Dries)] Then I need to have a check when I want to insert a new value in this array if the ID already is in the array or not. I currently have this:
$werknemers= [];
while($werknemer= $werknemersql->fetch_assoc()){
$werknemerid = $werknemer['userid'];
$naam = $werknemer['name'] ." " . $werknemer['familyname'];
array_push($werknemers, array("id" => $werknemerid, "naam" => $naam ));
}
echo $werknemers[1][1];

A simple technique to achieve that is to always update the array, with a consistent index:
$werknemers = [];
while($werknemer = $werknemersql->fetch_assoc()){
$werknemerid = $werknemer['userid'];
$naam = $werknemer['name'] . " " . $werknemer['familyname'];
$index = $werknemerid . '.' . $naam;
$werknemers[$index] = ["id" => $werknemerid, "naam" => $naam];
}
And then, if necessary, get rid of the indexes:
$werknemers = array_values($werknemers);

$werknemers= [];
while($werknemer= $werknemersql->fetch_assoc()){
$werknemers[$werknemer['userid']] = $werknemer['name'] . " " . $werknemer['familyname'];
}
Use id as index and it's solved :)

Related

How to create dynamic variables from SQL results

This one should be easy and it's killing me I can't find the solution!
I have a SQL query return records from a database. The two fields I am using are $row["staff_id"] and $row["name"].
From that I want to build a dynamic variable which is something like:
$staffid_1 = "Mark Smith";
$staffid_2 = "Sally Baker";
$staffid_3 = "Peter Pan";
The varibale name is created dynamically be combining "staffid_" and $row["staff_id"] for the first part then $row["name"] for the name.
I've tried:
${$staff_id . $row["staff_id"]} = $row["name"];
echo ${$staff_id . $row["staff_id"]} . "<br>";
But no luck! Any assistance would be appreciated :)
I would think you might be best to change your query to return the first part of it, then whatever you're calling it from to concatenate it together, eg
Query:
SELECT '$staffid_' + ltrim(rtrim(cast(staff_id as varchar))) + ' = "' + name + '"'
FROM [table list]
ORDER BY ...
Then concatenate the individual rows of result set as required, with in-between as you seem to require.
Okay so in PHP you have an awesome option to use a double leveled variable which basically means this :
$$varname = $value;
This results in the fact that if you have a string variable ,
(for example $staffid = "staffid_1") that you can do the following:
$staffid = "Jasonbourne";
$$staffid = "Matt Damon";
// Will result in
$JasonBourne = "Matt Damon";
So for your example:
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
Will result in the variable : $staff_id_1 = "Mark Smith";
To read more about double - leveled variables :
http://php.net/manual/en/language.variables.variable.php
EDIT: If you wanna loop through the rows :
foreach ($sql_result as $row) {
$name = "staffid_" . $row["staff_id"];
$$name = $row["name"];
}

PHP array output just first value

I am trying to write data from MySQL to PHP-Array (to generate a XML file with the PHP library FluidXML ). When I echo the array, I only get the first value of it, but when I echo a variable with the same data as the array I get correct output with all the information. Let me explain more exactly:
The query to get data:
$sql = sprintf("select b.nPosID, b.nAmount, b.sName, .......");
$result = mysql_query($sql);
Then I loop trough the results:
$msg = "";
$orderArticles = [];
$orderSubArticles = [];
while($data = mysql_fetch_array($result))
{
if($data['sChange'] != null) {
$msg .= ' * ' . $data['sChange'] . ' ' . number_format($data['nAmount'] * $data['nPriceChange'], 2) . "\r\n";
$orderSubArticles[] = ['SubArticle' => [
'ArticleNo' => '0',
'ArticleName' => $data['sChange'],
'Count' => $data['nAmount'],
'Price' => $data['nPriceChange']
],];
}
if ($nPosID != $data['nPosID']) {
$msg .= " \r\n" . $data['nAmount'] . ' x ' . $data['sName'] . ' ' . number_format($data['nAmount'] * $data['nPrice'], 2) . "\r\n";
$orderArticles[] = ['Article' => [
'ArticleNo' => '0',
'ArticleName' => $data['sName'],
'ArticleSize' => '0',
'Count' => $data['nAmount'],
'Price' => $data['nPrice'],
'Tax' => '10',
'SubArticleList' => [
$orderSubArticles
]],];
}
}
Let's assume, from the SQL query I get the following correct output:
Pizza
+ extra cheese
+ extra tonno
When I echo $msg variable, I get the same correct result. But when I echo the array, I only get the first value:
Pizza
+ extra cheese
To be exactly, the output which was generated with the values from the array:
<ArticleList>
<Article>
<ArticleName>Pizza</ArticleName>
<Count>1</Count>
<Price>12.9</Price>
<SubArticleList>
<SubArticle>
<ArticleName>Extra cheese</ArticleName>
<Count>1</Count>
<Price>3</Price>
</SubArticle>
</SubArticleList>
</Article>
</ArticleList>
So the second <SubArticle> is missing (extra tonno).
Without knowing how your resultset really looks like, I am doubting your assumption is correct, that a result/row in the set really contains both subarticles. That would lastly mean all results have two subarticles and that's supposingly not the case, because then it would need to return something like sChange1, sChange2 ...
Even if the results would look something like that and contain two or more sub articles, your code only assigns one of them to the subArticles-array per result.

Separate two array values from one key and insert to database in PHP

I designed the system for booking rooms and store the data by multi-dimensional array form.
Here is the array (data):
$recordBooking = array(
"111"=>array(
"date"=>array(
"29/10/2014"=>array(
array(
"from"=>1,
"to"=>3,
"user"=>"Amy",
"username"=>"CB34"
),
array(
"from"=>4,
"to"=>5,
"user"=>"Chars",
"username"=>"AA13"
)
),
"30/10/2014"=>array(
array(
"from"=>2,
"to"=>3,
"user"=>"Chars",
"username"=>"AA13"
),
array(
"from"=>3,
"to"=>6,
"user"=>"Gary",
"username"=>"SF11"
)
),
"02/11/2014"=>array(
array(
"from"=>1,
"to"=>3,
"user"=>"Billy",
"username"=>"V214"
)
),
.......
)
)
);
Also I was using the foreach-loop to separate the array values and store those data. And I using an array, $BookArrRecord, for gathering the values and insert into the database. It caused the error that $BookArrRecord can store the last values of each date only. Can anyone helps me to find out the problem and how to improve?
foreach($recordBooking as $key => $value){
$rmNum[] = $key;
foreach($value as $k => $v){
foreach($v as $bookDate => $array){
$bookingDate[] = $bookDate;
foreach($array as $room => $info){
foreach($info as $period =>$fromTo){
if($period=="username"){
$userID[] = $fromTo;
}
if($period=="from"){
$from[] = $fromTo;
}
if($period=="to"){
$to[] = $fromTo;
}
}
}
}
}
}
for($rmCount=1;$rmCount<count($userID);$rmCount++){//get the $userID to set the rows of $rmNum
$rmNum[]+=$rmID[0];
}
$BookArrRecord = array();
foreach($rmNum as $key => $value){
$BookArrRecord[] = "('" . $userID[$key] . "', '" . $rmNum[$key] . "', '". $bookingDate[$key] . "', '" . $from[$key] . "', '" . $to[$key] . "')";
}
The sql query:
$bookingInformation = "INSERT INTO `bookRecord` (`userID`, `room_Number`, `date`, `frome`, `to`)
VALUES " . implode(',', $BookArrRecord);
The checking of the query:
if(!mysql_query($bookingInformation, $dbConnection)){
die("Cannot access operation of Database(bookRecord): " . mysql_error()) . "<br>";
}else{
echo "Records added in table: BookingDate " . "<br>";
}
The results shows by using var_dump:
array(268) {
[0]=>
string(38) "('CB34', '111', '29/10/2014', '1', '3')"
[1]=>
string(38) "('AA13', '111', '30/10/2014', '4', '5')" //the date is wrong
[1]=>
string(38) "('AA13', '111', '02/11/2014', '2', '3')"
......
}
Thanks for any help.
I think your problem is that you have lots of different arrays ($userID, $rmNum, $bookingDate etc) which you're adding values to at different times. This makes it hard to keep track of which value in each array corresponds to which values in the other arrays. (It is possible, but tricky and likely leads to bugs).
An easier solution is to handle adding records to $BookArrRecord inside your foreach loops. That way you know that all the different values will be consistent.
For example:
$BookArrRecord = array();
$roomNumber = 1;
foreach($recordBooking as $key => $value){
$rmNum[] = $key;
foreach($value as $k => $v){
foreach($v as $bookDate => $array){
foreach($array as $room => $info){
$BookArrRecord[] = "('" . $info['username'] . "', '" . $roomNumber . "', '". $bookDate . "', '" . $info['from'] . "', '" . $info['to'] . "')";
$roomNumber++;
}
}
}
}
var_dump ($BookArrRecord);
Notice I've removed the innermost array. There's no need to loop over an array when you know which keys you're looking for.
As an aside, it's generally bad practice to include variables directly in a database query. You should escape them first. As this is a hardcoded array of values that you've specified, it's unlikely to go wrong now. But as soon as you start using any user-inputed values, make sure you escape them before they go anywhere near the query!

I want insert record into database but I get undefined index I write this code .php file

<?php
$action = $_POST['insert'];
$info_array = array();
$ItemCode = $_POST['ItemCode'];
$ItemName = $_POST['ItemName'];
$Quantity = $_POST['Quantity'];
$Rate = $_POST['Rate'];
$Total = $_POST['Total'];
echo $SqlPurchdtls = "insert into tblpurcdetails (itemId,itemQty,itemRate,TotalAmt)values
('" . $ItemCode . "','" . $Quantity . "','" . $Rate . "','" . $Total . "')";
$ResultPurchdtls = mysql_query($SqlPurchdtls);
//build the array that will store the item records
$info_array[] = array( 'idItem' => $idItem, 'ItemName' => $ItemName, 'Quantity' => $Quantity , 'Rate' => $Rate , 'Total' =>$Total);
echo json_encode($info_array); //convert the array to JSON string
?>
In this code value not inserted.I created database but value not posted.How to store values in the json array
Not really an answer, but too long for a comment:
First of all, never put $_POST (or any other) variables directly in your query. Always use mysqli_real_escape_string.
Secondly, mysql_xxx functions are deprecated. Please use mysqli_xxx.
Now that we have that out of the way, from the information you have given, it is impossible to see why the insert is not working. It also is not clear what your question is. Do you need help with the insert into database or help populating a json array?
Please provide the mysql error message and echo the generated sql. Are you connected to the right database? etc..
(Free tip: you can use compact to create the array $info_array more cleanly)

Convert a PHP array to an SQL statment?

I'm trying to convert an array (key/value) to be an SQL statement.
I'm using MYSQLi like such:
if(!$result = $mysqli->query($sql)){throw new Exception("SQL Failed ".__file__." on line ".__line__.":\n".$sql);}
I have an array like such:
Array
(
[database] => Array
(
[cms_network] => Array
(
[network_id] => 61
[network_name] =>
[network_server_mac_address] => 00:1b:eb:21:38:f4
[network_description] => network
[network_thermostat_reporting_rate] => 5
[network_server_reporting_rate] => 5
[network_data_poll_rate] => 5
[network_created_by] => 38
[network_modified_by] => 1
[network_network_id] => 8012
[network_language] => en
[network_hotel_id] => 68
[network_channel] => 0
[network_deleted] => 0
[network_reported_network_id] => 8012
[network_rooms] => 4
)
)
)
How can I convert [cms_network] to look like this:
$sql = "UPDATE cms_network set network_id='61', network_name='',
network_server_mac_address = '00:1b:eb:21:38:f4', .... WHERE network_id='61'"
I'm more interested in knowing how to concatenate the key=>value pair of the array to be key='value' in my select statement.
Thanks for the help!
If you use the VALUES syntax, you could do it in one fell swoop.
mysql_query("
UPDATE MyTable
( . implode(',', array_keys($array['database']['cms_network'])) . ")
VALUES ('" . implode("','", $array['database']['cms_network']) . "')
");
This, of course, assumes that the data is already escaped.
EDIT: Tidier version that's easier to read and maintain:
$fields = implode(',', array_keys($array['database']['cms_network']));
$values = implode("','", $array['database']['cms_network']);
mysql_query("UPDATE MyTable ($fields) VALUES ('$values')");
I suggest you populate an array with formatted key/value pairs, then implode them at the end. This is an easy way to add the required , between each key/value:
$fields = array();
foreach($array['database']['cms_network'] as $key => $value) {
// add formatted key/value pair to fields array
// e.g. format: network_id = '26'
$fields[] = $key . " = '" . $value . "'";
}
$fields = implode(', ', $fields);
// build your query
$query = "UPDATE cms_network SET " . $fields . " WHERE network_id = " . $array['database']['cms_network']['network_id'] . " LIMIT 1";
// process it...
This will (SQL wise) be inserting every value as a string, which is obviously incorrect with integer columns etc. It should still work anyway, but if not you'll need to put in a conditional statement for whether to wrap the value in quotes or not, like this:
foreach(...) {
if(is_numeric($value))
$fields[] = $key . ' = ' . $value;
else
$fields[] = $key . " = '$value'";
}
Although this should probably relate to your database column type rather than the PHP variable type. Up to you, they should work fine with quotes around integers.
This should work.
$update_query = "UPDATE `cms_network` SET ";
$count = 0;
foreach($array['database']['cms_network'] as $key => $value) {
if ($count != 0) {
$update_query = $update_query.",".$key."=".$value;
} else {
$update_query = $update_query.$key."=".$value;
}
$count++;
}
$update_query = $update_query." WHERE ".cms_network."=".$array['database']['cms_network'];
mysql_query($update_query);

Categories