why i have NULL when saving data in database - php

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

Related

Looping through Array Values with $SQL output

I have a list of serialized data that I unserialize and store into an array.
$employee_data = unserialize($entry, '63');
Which results in an expected output:
Array ( [0] =>
Array ( [First] => Joe
[Last] => Test
[Birth Date] => 01/01/2011
)
[1] =>
Array ( [First] => Mike
[Last] => Miller
[Birth Date] => 01/01/1980
)
)
Ive been trying, unsuccessfully, to insert these records into a table in MySQL using foreach() or something like:
$employee_array = array();
$k = 1;
for($n=0; $n<count($employee_data); $n++ ){
$employee_array['employee_first_name'.$k] = $employee_data[$n]['First'];
$employee_array['employee_last_name'.$k] = $employee_data[$n]['Last'];
$employee_array['employee_birthdate'.$k] = $employee_data[$n]['Birth Date'];
$SQL = "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
)
VALUES (
'$employee_first_name.$k',
'$employee_last_name.$k',
'$employee_birthdate.$k'
)"
$k++;
};
Each employee in the array needs to be entered into a new row in the table, however the number of employees will vary from 1 to 10+
We've tried
foreach($employee_array as $key => $value)
with the same results.
The actual results we're hoping for is the SQL Statement to be:
insert into employee_test(
employee_first_name,
employee_last_name,
employee_birthdate)
VALUES(
'Joe',
'Test',
'01/01/2011');
insert into employee_test(
employee_first_name,
employee_last_name,
employee_birthdate)
VALUES(
'Mike',
'Miller',
'01/01/1980');
Keep in mind that your sql statement is not escaped. For example, a name with an apostrophe like "0'neil" will break your sql. I would also familiarise yourself with php's foreach: https://www.php.net/manual/en/control-structures.foreach.php.
I'm not sure exactly what you're trying to accomplish by adding the index to the name and sql value, but I would do something like this:
foreach($employee_data as $key => $value){
// $employee_array is not necessary
$employee_array[$key]['employee_first_name'] = $value['First'];
$employee_array[$key]['employee_last_name'] = $value['Last'];
$employee_array[$key]['employee_birthdate'] = $value['Birth Date'];
// Needs escaping
$SQL = "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
)
VALUES (
'{$value['First']}',
'{$value['Last']}',
'{$value['Birth Date']}'
)";
echo $SQL;
};
The first implementation wont work as your calling a variable rather than the key in your array.
'$employee_first_name.$k',
Should be
$employee_array['employee_first_name'.$k]
You are also creating the SQL statement every iteration of the for loop, so in this implementation only the last employee will save.
Also I don't see the reasoning in doing it that way anyway you may as well just use the employee_data array and the $k variable can also be made redundant.
$SQL = "";
for($n=0; $n<count($employee_data); $n++ ){
$SQL .= "INSERT INTO employee_test (
employee_first_name,
employee_last_name,
employee_birthdate
) VALUES (";
$SQL .= "'".$employee_data[$n]['First']."',";
$SQL .= "'".$employee_data[$n]['Last']."',";
$SQL .= "'".$employee_data[$n]['Birth Date']."'";
$SQL .= ");";
};
Ive not tested but it should give you an idea.
You will also have issues with the date formatted that way, Your database would likely require the date in yyyy/mm/dd format
Finally I would not recommend inserting values like this, look at the PDO library for placeholders.
I think I understand what you're trying to do here. You are using the = operator, effectively setting $SQL to a new value each time your loop iterates. If you adapt your code, you will be able to append to $SQL variable each time.
//I used this array for testing. Comment this out
$employee_data = array(
0 => array(
"first" => "test",
"last" => "tester",
"birth date" => "01/01/1970"
),
1 => array(
"first" => "bob",
"last" => "david",
"birth date" => "02/02/1972"
),
);
//Start SQL as a blank string
$SQL = "";
//Do your iteration
foreach( $employee_data as $key=>$value ){
$first = $value['first'];
$last = $value['last'];
$birthDate = $value['birth date'];
//append this query to the $SQL variable. Note I use `.=` instead of `=`
$SQL .= "INSERT INTO employee_test(
`employee_first_name`,
`employee_last_name`,
`employee_birthdate`)
VALUES(
'$first',
'$last',
'$birthDate'
);";
}
//output the query
echo $SQL;
There are much easier ways of doing this though. Look into prepared statements :)

PHP array value to variable

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'];

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']; }

Assign Array Value to Variable and Insert into mysql using PHP

I am trying to save array value to variable so that I can insert that data/value into mysql using PHP for that I am using a pain taking long code so I want simple method to do it without writing it again and again.
Array shows data like this
Array
(
[0] => Array
(
[0] => a><p class="wp-caption-text">Pendant Heart Images</p></div>
[1] => a><p class="wp-caption-text">Pendant Heart Photos</p></div>
[2] => a><p class="wp-caption-text">Pendant Heart Photos</p></div>
)
[1] => Array
(
[0] => Pendant Heart Images
[1] => Pendant Heart Photos
[2] => Pendant Heart Photos
)
)
Code which I am using to save array value
$a = $g_img[1][0];
$b = $g_img[1][1];
$c = $g_img[1][2];
$a1 = $title[1][0];
$b1 = $title[1][1];
$c1 = $title[1][2];
Mysql query to save data
mysqli_query($con,"INSERT INTO data (Link, Title) VALUES ('$a','$a1')");
mysqli_query($con,"INSERT INTO data (Link, Title) VALUES ('$b','$b1')");
mysqli_query($con,"INSERT INTO data (Link, Title) VALUES ('$c','$c1')");
So If array data increases I have to assign each array value to different variable which is huge process I know there would be a shortcut
Plz Help
The query will not work because to start with, the number of field name are not equal to the number of values.
You could have passed your query in the following way:
for ($counter = 0; $counter <=2; $counter++){
$query = "INSERT INTO data (Link, Title) VALUES ('{$g_img[1][$counter]}', '{$title[1][$counter]}')";
$result = mysqli_query($con, $query);
}
Here I have assumed that $g_img and $title correspond to the array of links and titles respectively and the data connection is $con.

Multidimensional arrays to insert for one row

I have three arrays that look like this:
ingredientQTY is the first input box in each row, measurements is the select/dropdown in each row, and ingredientsNAME is the last input box in each row. As you can see, there can be infinite numbers of ingredientQTY's, ingredientNAME's, and measurements.
When I send them to my php script, the data is in arrays like:
IngredientQTY
(
[0] => 5 //The first row
[1] => 5 //The next rows value
)
Measurements
(
[0] => Bunch //The first row
[1] => Bunch //The next rows value
)
IngredientName
(
[0] => 5 //The first row
[1] => 5 //The next rows value
)
I'm trying to upload them to a table called ingredients that has 3 columns: ingredientNAME, ingredientQTY, and measurements.
In my php script, I'm combining them into a multidimensional array, which is assigned to $ingredientsROW:
foreach($_POST as $key => $value) {
$value = $this->input->post($key);
$ingredientQTY = $this->input->post('ingredientQTY');
$measurements = $this->input->post('measurements');
$ingredientNAME = $this->input->post('ingredientNAME');
$ingredientsROW[] = array($ingredientQTY, $measurements, $ingredientNAME);
break;
}
My question is: How can I get group all the first row of form elements (which means the first ingredientQTY, the first measurements dropdown and the first ingredientNAME and insert them into a row?
The only way I could think of is to have one insert where I insert ingredientQTY, then look up the id of the row I just inserted and use two mysql updates to enter for the same row, but I'm pretty sure there is more efficient ways of going about this.
Would something like this work?
foreach($_POST['IngredientQTY'] as $index=>$qty)
mysql_query("insert into ingredients ".
"set IngredientQTY='".addslashes($qty)."'".
", measurements ='".addslashes($_POST['measurements'][$index])."'".
", ingredientNAME ='".addslashes($_POST['ingredientNAME'][$index])."');
Iterate through the data and create an array like this:
for ($i = 0, $count = count($ingredientQTY); $i < $count; $i++) {
$rows[] = array(
'QTY' => $ingredientQTY[$i],
'measurement' => $measurements[$i],
'name' => $ingredientNAME[$i]
);
}
With this array you can create the insert quite easily and insert whole rows.

Categories