I'm trying to insert array into database. Why don't this work?
$array_zone = array();
$array_data = array();
while($row = mysql_fetch_array($keputusan1)){
$array_zone[] = $row['zone'];
$array_data[] = $row['data'];
}
echo "<pre>";
print_r($array_zone);
echo "<br>";
print_r($array_data);
echo "</pre>";
$list_zone = implode(",", $array_zone);
$list_data = implode(",", $array_data);
for($i = 0; $i < 4; $i++)
{
mysql_query("INSERT INTO `db`.`table1` (`id`, `domain`) VALUES ('$list_zone', '$list_data')");
}
Array output before implode:
Array
(
[0] => 270
[1] => 270
[2] => 255
[3] => 255
)
Array
(
[0] => ok.com.
[1] => lo.com.
[2] => i.com.
[3] => k.com.
)
Result I'm getting:
0 key should go with data in 0 key and 1 key should go with data in 1 key and so on... Help me please. Thank you.
You can use INSERT ... SELECT. The result returned in $keputusan1 is a SELECT query. And it certainly returns zone and data columns. Say the query is SELECT zone, data, columns ... FROM tbl1.
If you use INSERT ... SELECT the new query would be
INSERT INTO `db`.`table1` (`id`, `domain`) SELECT zone, data FROM tbl1";
This will SELECT first then INSERT it in one shot.
The problems with your code are
4 SQL statements. It should be 1.
You should use $array_zone and $array_data instead of $list_zone and $list_data if for loop is used. But it should not be as of step 1.
It seems to me, that you just forgot to use the loop-index ($i) within the loop
to access the arrays elements:
#!/usr/bin/php
<?php
$array_zone = array('a','b','c','d');
$array_data = array('1','2','3','4');
print_r($array_zone);
print_r($array_data);
for($i = 0; $i < count($array_zone); $i++)
{
echo("INSERT INTO `db`.`table1` (`id`, `domain`) VALUES ('$array_zone[$i]', '$array_data[$i]')\n");
}
?>
Now replace that echo with your mysql_query call and remove the '\n' at the end...
Your list_zone (really array_zone) is enclosed in a single set of single quotes, so you're passing one long string. And you're doing it four times. Pass it one pair of values at a time.
Are you sure you want to do this in that way? Probably a good idea to try the serialize() function instead of the implode. http://php.net/manual/en/function.serialize.php
Maybe an even better idea to use JSON for this task. http://php.net/manual/en/function.json-encode.php
Related
Hi i know its very simple but im stuck in this.
Im fetching data by using join from database.. Now i got the values in array. i want to add these two value in a variable.
Code is below..
$sql = "SELECT event_details.max_team_size FROM booking_details INNER JOIN event_details on booking_details.subcategory_id=event_details.id WHERE booking_details.`booking_id` = ".$booking_id." ";
$command = Yii::$app->db->createCommand($sql);
$array = $command->queryAll();
$array has got the values like this..
Array
(
[0] => Array
(
[max_team_size] => 6
)
[1] => Array
(
[max_team_size] => 8
)
)
I want to add these two max_team_size into a single variable and use that later to compare.
$sum = 0;
foreach($array as $data){
$sum += $data->max_team_size;
}
echo $sum;
Sum you can get from SQL also by using SUM function
SELECT SUM(event_details.max_team_size) FROM booking_details...
In Yii the solution will be
$sql = "SELECT SUM(event_details.max_team_size) as total FROM booking_details INNER JOIN event_details on booking_details.subcategory_id=event_details.id WHERE booking_details.`booking_id` = ".$booking_id." ";
$command = Yii::$app->db->createCommand($sql);
$array = $command->queryRow();
In PHP to sum particular key in single array you can convert it to single array by using array_column function and then use sum function
$array = array_column($array, 'max_team_size');
$total = array_sum($array);
Note: array_column will work PHP >= 5.5, for PHP < 5.5 you can use foreach loop
Define an empty array like this:
$maxArr = array();
You can run a foreach loop for your array now and add variable.
Like this:
foreach($gotArr as $key=>$val){
}
I'm currently working on a small University project and I have to get into PHP. I have a score table where I want to get a ranked list back in PHP. The query works in phpmyadmin, but I just can't get my head around the prepared statement and how to get the results out of it. Here my code:
$con = getConnection ();
if (!$con) {
exit();
}
$stmt = $con -> prepare("SELECT NICKNAME, HIGHSCORE, #curRank := #curRank + 1 AS RANK FROM scores p, (SELECT #curRank := 0) r ORDER BY HIGHSCORE DESC;");
$stmt->execute();
$result = $stmt->get_result(); //$result is of type mysqli_result
$num_rows = $result->num_rows; //count number of rows in the result
// the '=' in the if statement is intentional, it will return true on success or false if it fails.
if (!$result_array = $result->fetch_assoc()) {
}
for ($j=0; $j<=$num_rows ;$j++){
$rows[$j]=$result->fetch_row();
print_r($rows[$j]);
}
mysqli_close($con);
}
and this is how the print_r looks like:
Array ( [0] => guvtg [1] => 234 [2] => 2 ) Array ( [0] => guvtgloa [1]
=> 228 [2] => 3 ) Array ( [0] => guvtgloakkschmua [1] => 226 [2] => 4 ) Array ( [0] => guvtgloakk [1] => 182 [2] => 5 )
As you can see I'm getting the whole array, but I just want and output like this:
guvtg , 234 , 2
guvtgloa , 228 , 3
etc..
Does anybody know how to get a proper result? Thank you
If you want to use fetch_assoc() it will give you an associative array with each item corresponding to a row field; will return FALSE when you are beyond the last row.
while ( $row = $result->fetch_assoc() ) {
echo $row[ 'NICKNAME' ] . "," . $row['HIGHSCORE'] . "," . $row['RANK'];
// maybe echo something at the end of the line (another comma or a line break....)
}
You don't have to get the row count but you shoud check that $result is not FALSE.
Similarly if you don't care about column names you may use fetch_row
while ( $row = $result->fetch_row() ) {
echo implode( ',', $row );
// maybe echo something at the end of the line (another comma or a line break....)
}
This way you can use implode to pack the data in comma separated values.
(But you have to handle what character to put between each row in outout)
Ex. if you want rows separated by line breaks (that will produce a CSV file) put echo "\n"; as the last statement inside the loop.
If you want a stream of comma separated values (no line breaks) then one solution is this:
$first = true;
while ( $row = $result->fetch_WOR() ) {
if( $first ) { $first = false; } else { echo ","; }
echo implode( ',', $row );
// maybe echo something at the end of the line (another comma or a line break....)
}
You'll allways get arrays from a database query, but it sounds like you just want to format the output differently. You could try this:
change
print_r($rows[$j]);
into
echo implode(', ', $rows[$j]), "\n";
implode will join the elements of every array with a comma+space in between, and by putting a newline after every record, the rows will each go on their own line.
Thanks for helping as always.
My code generates arrays in the following format
${'readyformerge' . $b} = $temparraytwo;
Which results in the array names of
$readyformerge1
$readyformerge2
$readyformerge3
etc...
Which works well and we know the value that $b holds is the amount of arrays we need to merge. However I can't quite see how to do this when we won't know prior to running the script how many arrays will be created.
Fundamentally I would like to use the following to grab the result but as you see I can only do this for the amount of results I THINk it will return NOT the actual number of results. Any help?
$outputmultidimensionalevent = array_merge_recursive(${'readyformerge' . $b},${'readyformerge' . $b});
print_r($outputmultidimensionalevent); echo '<br/>';
Your problem is the result of bad design.
Instead of:
${'readyformerge' . $b} = $temparraytwo;
You should do something like this:
$readyformerge[$b] = $temparraytwo;
And then:
$merged = array();
foreach ($readyformerge as $one) {
$merged = array_merge($merged, $one);
}
Thanks, That's pushed me in the right direction.
So currently it's now setup like this:
$z=1;
$readyformergemulti = array();
while ($z <= $i){
array_push($readyformergemulti,${'readyformerge' . $z});
$z++;
}
foreach ($readyformergemulti as $one) {
print_r($one);
echo '<br/>';
$merged = array_merge_recursive($merged, $one);
}
print_r($readyformergemulti); echo '<br/>';
print_r($merged); echo '<br/>';
But unfortunately $merged returns nothing. If you look at the following the first 4 lines are the $readyformerge arrays and the 5th line is the desired result:
Array ( [house] => 2797 )
Array ( [house] => 2829 )
Array ( [house] => 2736 )
Array ( [electronica] => 2763 [house] => 2763 )
Array ( [electronica] => Array (2763) [house] => Array (2763,2797,2892,2736 ) )
Sorry to be a pain, and I KNOW everyone needs to see more code, but with thousands of lines it gets hard to display!
If you can help again that would be great!
I have created this
while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
print_r($data['course']);
}
Which prints this:
Array (
[user_id] => 57
[course] => 6
)
Array (
[user_id] => 57
[course] => 5
)
How can I create two variables that are equal to the values of the 'course' fields.
So ideally, variable x ends up equalling to 6 and variable y equals 5 (essentially what I'm asking is how to extract the value from the mysql arrays and putting it into a variable)?
There is no something as you called "mysql_arrays". They are normal arrays.
You can do for example:
$array = array();
while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
$array[] = $data; // probably this way and not $array[] = $data['course'];
}
$x = $array[0]['course'];
$y = $array[1]['course'];
I would suggest you using an array instead of a variable to store the values.
$arr= array();
while ($data = mysqli_fetch_array($course_result, MYSQLI_ASSOC)) {
$arr[] = $data['course'];
}
Speculating a bit as don't have the full picture but I guess you're after something like this.
Get an array of the courses from your data
$data = array_map(function($value) {
return $value['course'];
}, $data);
If there are only ever two results, assign each one to a variable :
list($x, $y) = $data;
If there are more than two results, you have an array of courses in $data from your query results.
I have 2 arrays - the first one is output first in full. The 2nd one may have some values that were already used/output with the first array. I want to "clean up" the 2nd array so that I can output its data without worrying about showing duplicates. Just to be sure I have the terminology right & don't have some sort of "array within an array", this is how I access each one:
1st Array
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem) {
echo $firstResponseItem['samecolumnname']; // Don't care if it's in 2nd array
}
2nd Array
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname']; //This can't match anything above
}
}
Thanks!
For example:
$response_names = array();
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem)
$response_names[] = $firstResponseItem['samecolumnname'];
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem) {
if (!in_array($secondResponseItem['samecolumnname'], $response_names))
$response_names[] = $secondResponseItem['samecolumnname'];
}
}
array_walk($response_names, function($value) { echo $value . '<br />' });
If I understand what you're looking to do and the arrays are in the same scope, this should work.
$secondResponseArray = array($secondResponseRow);
$secondResponseArray = array_diff($secondResponseArray, $firstResponse);
//secondResponseArray now contains only unique items
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname'];
}
If you know that the keys of duplicate values will be the same you could use array_diff_assoc to get the items of the first array that aren't in the other supplied arrays.
This code
<?php
$a = array('abc', 'def', 'ghi', 'adg');
$b = array('abc', 'hfs', 'toast', 'adgi');
$r = array_diff_assoc($b, $a);
print_r($a);
print_r($r);
produces the following output
[kernel#~]php so_1.php
Array
(
[0] => abc
[1] => def
[2] => ghi
[3] => adg
)
Array
(
[1] => hfs
[2] => toast
[3] => adgi
)
[kernel#~]