PDO fetchAll array to one dimensional - php

this may be a simple question but am struggling to understand how to solve it. I have a form which allows the user to select either "custom" or "all" staff" to assign to a job.
If custom is selected the user selects staff by clicking each checkbox, I then insert these into a jobs table. This produces the array below (3, 1, 10 are the staff IDs)
Array
(
[0] => 3
[1] => 1
[2] => 10
)
If "all staff" is selected, I first query a select statement to get all the staff ID's from the staff table, and then insert these into the job table the same as above. However this produces the array :
Array
(
[0] => Array
(
[staffID] => 1
[0] => 1
)
[1] => Array
(
[staffID] => 23
[0] => 23
)
[2] => Array
(
[staffID] => 26
[0] => 26
)
[3] => Array
(
[staffID] => 29
[0] => 29
)
)
How can I convert the array above to the first array shown?
I'm using the code below to query the database to get all the staff ID's and then inserting them.
$select = $db->prepare("SELECT staffID FROM staff");
if($select->execute())
{
$staff = $select->fetchAll();
}
for($i = 0; $i<count($staff); $i++)
{
$staffStmt = $db->prepare("INSERT INTO staffJobs (jobID, userID) VALUES (:jobID, :staffID)");
$staffStmt->bindParam(':jobID', $jobID, PDO::PARAM_INT);
$staffStmt->bindParam(':staffID', $staff[$i], PDO::PARAM_INT);
$staffStmt->execute();
}
The first array inserts fine, however the last array inserts zeros for the staffID.
Any suggestions?
Thanks =).

Take a look at example 2 in the manual. In your first query you can use:
$staff = $select->fetchAll(PDO::FETCH_COLUMN, 0);
And your second array will have the same form as the first array.

If you print_r($staff[$i]) inside the for you would probably get
Array
(
[staffID] => 1
[0] => 1
)
which means you should use $staff[$i]['staffID'] instead.
The other alternative, which should work with your current code, is to use PDOStatement::fetchColumn() instead of fetchAll().

You need to give fetchAll a fetch style
$staff = $select->fetchAll(PDO::FETCH_NUM);
From this link

Related

Remove First Filed in Array and insert MySQL

i have one array i want insert mysql database.
Array ( [posts] => Array ( [0] =>
Array ( [channel_id] => 18560 [category_id] => 41 [channel_name] => Bohemian FC 1 - 1 Chelsea [channel_image] => IMG-20190416-WA0087.jpg [channel_url] => nourl [channel_description] => [channel_type] => URL [video_id] => [category_name] => Last day Matches ) [1] =>
Array ( [channel_id] => 18559 [category_id] => 41 [channel_name] => Nigeria 2 - 1 South Africa [channel_image] => IMG-20190416-WA0087.jpg [channel_url] => nourl [channel_description] => [channel_type] => URL [video_id] => [category_name] => Last day Matches ) ) )
Array ( ) Array ( ) Array ( ) Array ( )
insert.php
foreach($array as $row) //Extract the Array Values by using Foreach Loop
{
$query .= "INSERT INTO tbl_channel(category_id,channel_name, channel_image,channel_url,channel_description,channel_type,video_id) VALUES ('".$row["category_id"]."', '".$row["channel_name"]."', '".$row["channel_image"]."', '".$row["channel_url"]."', '".$row["channel_description"]."', '".$row["channel_type"]."', '".$row["video_id"]."'); "; // Make Multiple Insert Query
table_data .= '<tr></tr>';
}
if(mysqli_query($connect, $query)) //Run Mutliple Insert Query
{
echo '<h3>Imported Data</h3><br />';
}
I cant Insert values in MySQL Table. I Have Getting Error Illegal string offset 'category_id' what Error My Code(Sorry bad Language )
Inside your loop that builds the query string, add a quick check to see if the correct array elements exist, and only add them to the query string if they do.
if (isset($row['category_id'])) {
// add the row to the query string
}
Then as #Qirel said, you can't run more than one query, so you need to call mysqli_multi_query() instead.
Also as #Qirel noted, this kind of thing is an ideal place to use prepared statements. Prepare the query before the loop, then call it with the different parameter values inside the loop. It adds a level of security against vulnerability and maybe a small performance increase.

How to store MYSQLI query as multidimensional array in this format [duplicate]

This question already has answers here:
get array of rows with mysqli result
(2 answers)
Closed 4 years ago.
I'm trying to query database A and store results as an array, which I will then insert into database B. I can move simple data directly, but because of the complexity of this particular query (30+ left joins), I have to store it as an array and insert it in a separate query. The examples below contain just two fields, to keep things simple and focus on the core issue.
I have working code to insert an array stored as follows:
$data = array(
array( // record 1, or row 1
"1",
"Value for field 1.2"
),
array( // record 2, or row 2
"2",
"Value for field 2.2"
),
array( // record 3, or row 3
"3",
"Value for field 3.2"
),
// etc...
);
Unfortunately, I can't get my first query to store the data like this. I have used PHP for years, but I never messed with arrays before. I'm not sure what I'm doing wrong. Using "print_r($data), this is what the results look like for how I need the array to be (This is what the $data variable looks like with print_r() ):
Array ( [0] => Array ( [0] => 1 [1] => Value for field 1.2 ) [1] => Array ( [0] => 2 [1] => Value for field 2.2 ) [2] => Array ( [0] => 3 [1] => Value for field 3.2 ) )
My query to create the array doesn't match this pattern. A "print_r($new_array)" command yields this:
Array ( [0] => Array ( [id] => 37 [post_title] => test1 ) [1] => Array ( [id] => 38 [post_title] => test2 ) [2] => Array ( [id] => 35 [post_title] => test3 ) [3] => Array ( [id] => 42 [post_title] => test4 ) [4] => Array ( [id] => 44 [post_title] => test5 ) [5] => Array ( [id] => 46 [post_title] => test6 ) )
This is my MySQL query to put the data into an array:
$test_sql = "SELECT id, post_title FROM wp_posts where post_type LIKE 'test'";
$resultTest = mysqli_query($con, $test_sql);
//$new_array[] = $row;
while ($row = mysqli_fetch_assoc($resultTest)) {
$rows[] = $row;
}
If I understand what is going on, the array I'm creating is making key value pairs for a multidimensional array, but the format I need is not key value, just an array of values. Since I already have the insert query working, I would prefer to use a select query that stores the data in an array without the key value pairs, if that is possible, but I am open to all suggestions.
Thank you in advance for your kindness and help!
All you need to do is change fetch function to fetch_row:
while ($row = mysqli_fetch_row($resultTest)) {
$rows[] = $row;
}
Or to fetch_array with MYSQLI_NUM as second argument:
while ($row = mysqli_fetch_array($resultTest, MYSQLI_NUM)) {
$rows[] = $row;
}

How can I get single element of the array in PDO? [duplicate]

this may be a simple question but am struggling to understand how to solve it. I have a form which allows the user to select either "custom" or "all" staff" to assign to a job.
If custom is selected the user selects staff by clicking each checkbox, I then insert these into a jobs table. This produces the array below (3, 1, 10 are the staff IDs)
Array
(
[0] => 3
[1] => 1
[2] => 10
)
If "all staff" is selected, I first query a select statement to get all the staff ID's from the staff table, and then insert these into the job table the same as above. However this produces the array :
Array
(
[0] => Array
(
[staffID] => 1
[0] => 1
)
[1] => Array
(
[staffID] => 23
[0] => 23
)
[2] => Array
(
[staffID] => 26
[0] => 26
)
[3] => Array
(
[staffID] => 29
[0] => 29
)
)
How can I convert the array above to the first array shown?
I'm using the code below to query the database to get all the staff ID's and then inserting them.
$select = $db->prepare("SELECT staffID FROM staff");
if($select->execute())
{
$staff = $select->fetchAll();
}
for($i = 0; $i<count($staff); $i++)
{
$staffStmt = $db->prepare("INSERT INTO staffJobs (jobID, userID) VALUES (:jobID, :staffID)");
$staffStmt->bindParam(':jobID', $jobID, PDO::PARAM_INT);
$staffStmt->bindParam(':staffID', $staff[$i], PDO::PARAM_INT);
$staffStmt->execute();
}
The first array inserts fine, however the last array inserts zeros for the staffID.
Any suggestions?
Thanks =).
Take a look at example 2 in the manual. In your first query you can use:
$staff = $select->fetchAll(PDO::FETCH_COLUMN, 0);
And your second array will have the same form as the first array.
If you print_r($staff[$i]) inside the for you would probably get
Array
(
[staffID] => 1
[0] => 1
)
which means you should use $staff[$i]['staffID'] instead.
The other alternative, which should work with your current code, is to use PDOStatement::fetchColumn() instead of fetchAll().
You need to give fetchAll a fetch style
$staff = $select->fetchAll(PDO::FETCH_NUM);
From this link

Put multi array into mysql

Hi i got this array here and i want to put it into mysql database,
here is my array
$v = "Tom: 2000, Bob: 300, Jack: 500"
$x is Array ( [0] => Array ( [0] => Tom [1] => 2000 ) [1] => Array ( [0] => Bob [1] => 300 ) [2] => Array ( [0] => Jack [1] => 500 ) )
and this is my code to put it into database:
$f=explode(",",$v);
for($i=0;$i<sizeof($f);$i++){
$x[$i]=explode(": ",$f[$i]);
$player=$x[$i][0];
$win=$x[$i][1];
$sql = "UPDATE scores SET win=$win WHERE player='$player'";
$result = $conn->query( $sql );
}
but the problem is for loop only puts 'Tom' and '2000' (which are first) into database and nothing happens to other player's row, i think this code should work fine but i cant find what is the problem.
Do the other records exist? I see you're doing an UPDATE and not an INSERT, so maybe the other records mismatch on "player"?
You also might want to use trim() on $player and $win, to remove any whitespace from the explode() output.

trying to get a multi table sql query into one result array

I have four tables: followers, users, mixes, songs I am trying to get all the mixes from all the followers of one user, I have that part figured out, but I also want to get the songs from each of those mixes, currently my query is giving me results but each result is for one song on the mix, rather than an array of songs within each result for one mix ... any help would be amazing, my sql skills aren't the greatest and I have spent a lot of time trying to figure this out!
my current query is:
SELECT followers.following_id, users.id, users.user_username, mixes.id, mixes.mix_created_date, mixes.mix_name,songs.song_artist
FROM followers, users, mixes,songs
WHERE followers.user_id = 46
AND users.id = followers.following_id
AND mixes.user_id = followers.following_id
AND mixes.id > 0
ORDER BY mixes.mix_created_date DESC
LIMIT 10
the current result is (from running this through a cakephp custom query)
Array
(
[0] => Array
(
[followers] => Array
(
[following_id] => 47
)
[users] => Array
(
[id] => 47
[user_username] => someguy
)
[mixes] => Array
(
[id] => 45
[mix_created_date] => 2012-07-21 2:42:17
[mix_name] => this is a test
)
[songs] => Array
(
[song_artist] => Yo La Tengo
)
)
[1] => Array
(
[followers] => Array
(
[following_id] => 47
)
[users] => Array
(
[id] => 47
[user_username] => someguy
)
[mixes] => Array
(
[id] => 45
[mix_created_date] => 2012-07-21 2:42:17
[mix_name] => this is a test
)
[songs] => Array
(
[song_artist] => Animal Collective
)
)
as you can see the mix id's are the same, I am trying to get the songs to be an array inside of each result like :
Array
(
[0] => Array
(
[followers] => Array
(
[following_id] => 47
)
[users] => Array
(
[id] => 47
[user_username] => someguy
)
[mixes] => Array
(
[id] => 45
[mix_created_date] => 2012-07-21 2:42:17
[mix_name] => this is a test
)
[songs] => Array
(
[0]=>array(
['song_artist'] => Yo La Tengo
),
[1]=>array(
['song_artist'] => Animal Collective
)
)
)
Really hoping this can be done with just one sql statement! thanks in advance!
You can use the SQL join command to make multiple queries together..
Use this...
sql_join
first a note: it looks like you have a missing condition. according to the above query, every song in songs table will be joined with every result possible. probably there should be a condition similar to the following added: (column names can be different based on your tables):
...
and mix.song_id=songs.song_id
...
as for your question: I don't know php so i regard mysql alone: I don't think it is possible to do it with mysql. mysql returns rows in the result set and each row can contain a single value in each column. to add a group of values (song names) in one column, they must be concatenated (and that is possible: Can I concatenate multiple MySQL rows into one field?), and later you split them back in your php script. this is not a good idea as you will need to choose a separator that you know will never appear in the values that are concatenated. therefore I think its better to remove the songs table from the query and after getting the mix id, run a second query to get all songs in that mix.

Categories