Insert array in to MySQL with PHP - php

I am trying to insert an array in to MySQL using PHP. I followed the excellent advice given on here to use the implode command and it worked great for one array, but this one seems to be dying. This array is slightly different than the other, but I don't know how to explain the difference.
Here is my code:
$sql = array();
foreach( $ride_detail as $row ) {
$sql[] = '('.$row['id'].', "'.mysql_real_escape_string($row['name']).'",
"'.$row['version'].'")';
}
mysql_query('INSERT IGNORE INTO ride (ride_id, name, version) VALUES '.implode(',', $sql));
I'm getting this message over and over again.
Warning: Illegal string offset 'id' in ride_details.php on line 60
Warning: Illegal string offset 'name' in ride_details.php on line 60
Warning: Illegal string offset 'version' in ride_details.php on line 61
The content of my array (using print_r) is:
Array ( [id] => 21570117 [name] => Night ride home from work [start_date_local] => 1347302039 [elapsed_time] => 53:56 [moving_time] => 52:04 [distance] => 12.6 >>[average_speed] => 14.5 [elevation_gain] => 474 [location] => Englewood, CO [start_latlng] => Array ( [0] => 39.547792011872 [1] => -104.86300536431 ) [end_latlng] => Array ( [0] => 39.655485888943 [1] => -104.88656991161 ) [version] => 1355428869 [athlete] => Array ( >>[id] => 832001 [name] => Bob Kratchet [username] => bob_kratchet ) [bike] => Array ( [id] => 281303 [name] => Giant Allegre commuter ) [maximum_speed] => 29.3 [calories] => 372 >[average_power] => 107 [commute] => 1 )
I am a complete noob...

Since your $ride_detail is just one array, $row is 21570117 (integer), Night ride home from work (string), and so on, one by one. The code then attempts to get the id key of each element, then the name key, and so on, generating a [expletive]-ton of error messages as it goes.
It looks like you're intending to have $ride_detail be an array of arrays, or you don't actually want a foreach loop at all.

try this
foreach( $ride_detail as $row ) {
$sql = array( $row['id'], mysql_real_escape_string($row['name']), $row['version']) ;
}
mysql_query('INSERT IGNORE INTO ride (ride_id, name, version) VALUES ($sql[0] ,$sql[1] , $sql[2] ) ');

Related

PHP replace characters in array

I'm trying to replace quotes and others characters from a mysql result array, using strtr() function. But i got Warning: strtr() expects parameter 1 to be string, array given and null values.
Heres my code:
while($rows = mysqli_fetch_assoc($list)){
$string_filter = array(';'=>'','['=>'',']'=>'','{'=>'','}'=>'','"'=>'',"'"=>'');
$data[$rows['id']] = strtr($rows,$string_filter);
}
$data is an array that i want to remove/trim the characters specified in $string_filter array. Heres the content sample from $data:
Array ( [1] => Array ( [id] => 1 [user_id] => 204554 [name] => Rich [group] => PL [ai] => BA [image] => 204554-35849.jpg ) [2] => Array ( [id] => 2 [user_id] => 124534 [name] => James [group] => SS [ai] => IT [image] => 123141-12312.jpg )...
Quick Question, are you sure these characters actually exist in your data? Because the characters you are trying to remove are the ones php will automatically append to an array when that array is viewed via the print_r function. To be precise this statement
print_r(array('key' => 'value'));
will output
Array([key] => value)
even tough there is no actual [ or ] present in the arrays data itself.
In any case this code snippet will clean the keys and values of your array:
$string_filter = array(';'=>'','['=>'',']'=>'','{'=>'','}'=>'','"'=>'',"'"=>'');
while($rows = mysqli_fetch_assoc($list)){
$cleanedrow = [];
foreach($rows as $key => $value) {
$cleanedrow[strtr($key, $string_filter)] = strtr($value, $string_filter);
}
$data[$rows['id']] = $cleanedrow;
}

Add element to PHP associative array in loop

I've looked but can't find an answer for my specific use case. I want to add an element to a multidimensional array while looping through it. What I have before the loop:
Array
(
[fname] => Monty
[lname] => Python
[phone] => 555 555 1212
[email] => a#b.com
[modelList] => Array
(
[0] => Array
(
[id] => 1
[modelName] => X-Wing
[remarks] =>
[htmlRemarks] =>
[category] => Vehicles
[catID] => 178
[attachedToBase] => 1
[oversized] => 0
)
)
)
In code, I'm looping through the [modelList] array and after doing some database operations what I want to do is append new elements to each model array - in the case below, the [dbID]:
Array
(
[fname] => Monty
[lname] => Python
[phone] => 555 555 1212
[email] => a#b.com
[modelList] => Array
(
[0] => Array
(
[id] => 1
[modelName] => X-Wing
[remarks] =>
[htmlRemarks] =>
[category] => Vehicles
[catID] => 178
[attachedToBase] => 1
[oversized] => 0
[dbID] => 907
)
)
)
All inputs are from a form POST, and in my php handler:
// Loop thru model entries
$modelList = json_decode($_POST["modelList"], TRUE);
foreach($modelList as $model) {
(do some work)
// Add the new element
array_push($model['dbID'], $newID);
}
But this throws an error:
PHP Warning: array_push() expects parameter 1 to be array, null given
How can I add the new element to the sub-array?
array_push
Push one or more elements onto the end of array
You can't add a key value item to an array using array_push.
Use this instead :
foreach ($modelList as $key => $model){
$modelList[$key]['dbID'] = $newID;
}
Based on your snippet with the loop are you trying to actually update the dbID?
If so, you should change the logic to:
foreach ($modelList as $key => $model) {
(do some work)
$modelList[$key]['dbID'] = $newID;
}
Why:
you cannot change contents of the array you are looping over (unless accessed by reference)
in your example code $model['dbID'] is number 907 which is not an array, hence the error message
Found it - I needed to use a reference to $model in order to update it
// Loop thru model entries
$modelList = json_decode($_POST["modelList"], TRUE);
foreach($modelList as &$model) {
(do some work)
// Add the new element
$model['dbID'] = $newID;
}
unset($model);

Get session values with the same index tag and select the bigger int value

I have a session variable called $_SESSION["shopping_cart"] which saves an array formed by user defined selections on a web page (meaning: products, codes, prices, descriptions and number of active months).
The array will look something like "Array => Array1["xxx"]=> ['product'] = "xxx", ['detail'] = "xxxxx", ['price'] = "xxx", ['envios'] = "x", Array2 => ...... and goes on. Now, SOME of the arrays in there will have an index ['envios'] = "x" and some of them won't. This specific index is always an INT value between 1-12. I need to select all of the values with a index ['envios'] and then save the bigger one of them in a separated variable $corval.
Is there any way to do that?
I found several session functions as session_search() or session_value() BUT all of them will return the value of the index when the input is equal to some array value. And I need to do it the other way around.
Long story short, I need to get all the values for the index ['envios'] inside the session array and save only the bigger of them into a different variable in php. If there is no ['envios'] index the the variable will be equal to 1.
This is the actual array data:
Array ( [BTWL001] => Array ( [name] => P�lulas Winky Lux [code] => BTWL001 [price] => 95.00 [quantity] => 1 [stock] => 8 [image] => /bubale/img/productimg/set5winki.jpg ) [PB001] =>
Array ( [name] => BOLSINHA UNICA [code] => PB001 [price] => 130.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/1month.png [envios] => 1 ) [PB003] =>
Array ( [name] => PLANO TRIMESTRAL [code] => PB003 [price] => 300.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/3month.png [envios] => 3 ) [PB012] =>
Array ( [name] => PLANO ANUAL [code] => PB012 [price] => 1080.00 [quantity] => 1 [stock] => 9999 [image] => /bubale/img/12month.png [envios] => 12 ) )
Note that there are 3 arrays with the index tag ['envios']. This array is stored in a session so I need to get only those "['envios']" values.
well, after a lot of research I found a solution to this problem, so for those in search of something like this, here we go:
$col = $_SESSION['your session variable'];
$env = array_column($col, 'name of the index you need to extract');
// here the $env will have a new array with only the values identified with the index you looked up for) //
$final = max($env);
//you saved the maximum value of the array//

Notice: Undefined index backdrop_path

i want display the backdrop_path of the movie but i get this error
Notice: Undefined index: backdrop_path in /..../public_html/movie.php on line 167
I have added
print_r($tmdbResult);
to see the content of $tmdbResult. I want to display just backdrop_path.
Array
(
[movie_results] => Array
(
[0] => Array
(
[adult] =>
[backdrop_path] => /mbA7SCtJoFTactP1lDHA055qCf.jpg
[genre_ids] => Array
(
[0] => 35
[1] => 28
)
[id] => 261392
[original_language] => en
[original_title] => American Ultra
[overview] => A stoner and his girlfriend's sleepy, small-town existence is disrupted when his past comes back to haunt him in the form of a government operation set to wipe him out.
[release_date] => 2015-08-21
[poster_path] => /6oGHH27nqaLGfpcgYRIZYSJs7AD.jpg
[popularity] => 3.509263
[title] => American Ultra
[video] =>
[vote_average] => 5.6
[vote_count] => 134
)
)
[person_results] => Array
(
)
[tv_results] => Array
(
)
[tv_episode_results] => Array
(
)
[tv_season_results] => Array
(
)
)
The code i use is
ini_set("display_errors",1);
$tmdbResponse = curl_exec($ch);
curl_close($ch);
$tmdbResult = json_decode($tmdbResponse, true );
$backdrop_path = $tmdbResult['movie_results']['backdrop_path'];
$smarty->assign("backdrop_path",$backdrop_path);
print_r($tmdbResult);
The reason is you're getting a numeric index, because the result can contain multiple movies. In this case you're getting just one.
All you need to do is access the array like this #u_mulder said:
$bp = $tmdbResult['movie_results'][0]['backdrop_path'];
The [0] meaning that in case you get multiple results, just need to change that index to access the others. May be you shoulds think of a foreach loop, unless for some reason of yours, you KNOW you'll always get ONE single movie, in that case, hardcode your $bp = $tmdbResult['movie_results'][0]['backdrop_path']; no problem.

PDO fetchAll() primary key as array group key

I want to store the contents of a specific database into an array, grouped by their primary keys. (Instead of the useless way PDO fetchAll() organises them).
My current code:
$DownloadsPDO = $database->dbh->prepare("SELECT * FROM `downloads`");
$DownloadsArray = $DownloadsPDO->execute();
$DownloadsArray = $DownloadsPDO->fetchAll();
Which then outputs:
Array ( [0] => Array ( [id] => 0 [0] => 0 [path] => /xx-xx/testfile.zip [1] => /xx-xx/testfile.zip [name] => Test Script [2] => Test Script [status] => 1 [3] => 1 ) [1] => Array ( [id] => 1 [0] => 1 [path] => /xx-xx/test--file.zip [1] => /xxxx/testfile.zip [name] => New Script-UPDATE [2] => New Script-UPDATE [status] => 1 [3] => 1 ) )
I was considering to use PDO::FETCH_PAIR, however I will be very soon expanding the amount of data I want to be able to use on this script. This works currently, but when I start to expand the amount of downloads and more clients come into play, obviously the way the data is grouped causes an issue.
Is it possible for me to group each array by their primary key (which is id)?
You can just use
$results = array_map('reset', $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC))
PDO::FETCH_GROUP|PDO::FETCH_ASSOC returns an array of arrays. The first column is used as the key, and then within key is an array of all the results for that key. However, in our scenario each key will only contain 1 row. reset() returns the first element in array, thus eliminating 1 level of nesting.
This should yield what you are looking for :
$results = $pdos->fetchAll(\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);
I decided to just loop through the results with fetch() and enter them into an array as I go along, this is the code I have used and it works just fine:
$DownloadsPDO = $database->dbh->query("SELECT * FROM `downloads`");
$Array = array();
while ($d = $DownloadsPDO->fetch()) {
$Array[$d['id']]["id"] = $d['id'];
$Array[$d['id']]["name"] = $d['name'];
$Array[$d['id']]["path"] = $d['path'];
}
// Outputs
Array ( [1] => Array ( [id] => 1 [name] => Test Script [path] => /xxxx/testfile.zip ) [2] => Array ( [id] => 2 [name] => New Script-UPDATE [path] => /xxxx/testfile.zip ) )
Which uses the primary key (being id) as the name for the array key, and then adds the data into it.
Thought I would add this as the answer as this solved it, thanks to the guys that helped out and I hope this is helpful to anyone else hoping to achieve the same thing.
I'd like to point out the only solution that works for me:
fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);
Beware that this will strip the first column from the resultset. So the query must be:
SELECT id_keyname AS arrkey, id_keyname, .... FROM ...
I'm still suggesting you to loop using fetch() method. Otherwise, you can use array_reduce() to iterate over the array. A sample on codepad is here.
The code(in human readable form) will be:
$myFinalArray = array_reduce($myInputArray, function($returnArray, $temp) {
$temp2 = $temp['id'];
unset($temp['id']);
$returnArray[$temp2] = $temp;
return $returnArray;
}
);
So, my question is; is it possible for me to group each array by their
primary key (which is id)
Off course, you have 2 options here: Either to change the query or parse a result-set.
So, I'm sure you don't want to change query itself, so I'd go with parsing result-set.
Note:
You should use prepared SQL statements when they make sense. If you want to bind some parameters then its OKAY. But in this case, you only want get get result-set, so prepare() and fetch() will be kinda overdo.
So, you have:
Array ( [0] => Array ( [id] => 0 [0] => 0 [path] => /xx-xx/testfile.zip [1] => /xx-xx/testfile.zip [name] => Test Script [2] => Test Script [status] => 1 [3] => 1 ) [1] => Array ( [id] => 1 [0] => 1 [path] => /xx-xx/test--file.zip [1] => /xxxx/testfile.zip [name] => New Script-UPDATE [2] => New Script-UPDATE [status] => 1 [3] => 1 ) )
And you want:
Array( [id] => Array('bar' => 'foo') ....)
Well, you can do something like this:
$stmt = $database->dbh->query("SELECT * FROM `downloads`");
$result = array();
foreach($stmt as $array){
$result[$array['id']] = $array;
}
print_r($result); // Outputs: Array(Array('id' => Array(...)))

Categories