Put multi array into mysql - php

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.

Related

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

show random values from array of array

Below is a array generated by a query builder.
$random_array = Array ( [0] => Array ( [text] => A great time was had by all! )
[1] => Array ( [text] => KILL SHOT )
[2] => Array ( [text] => How is it possible)
[3] => Array ( [text] => http://www.youtube.com/watch?v=KwGOZpbxU9g )
[4] => Array ( [text] => http://www.youtube.com/watch?v=KwGOZpbxU9g )
)
Currently i am doing like this to print the random value
print_r(array_rand($random_array,1));
This is printing the array key as 3 or 1 etc(random from above array).I want to print the value of the key and not the key.
e.g I want to print the random value like this "http://www.youtube.com/watch?v=KwGOZpbxU9g" or "A great time was had by all!" instead of 3 or 1 which is printing now.
Is it possible to do this.
You will have one more line of code as shown below:
$array_key = array_rand($random_array,1); //get the key
print_r( $random_array[$array_key] ); //use the key to print value
What about simply calling
$randNumber = rand(0,count($random_array))-1; //index in array starts with 0
print (string) $random_array[$randNumber];

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

echoing array from fql.multiquery

PHP / FACEBOOK'S FQL
Thank you for even reading this.
I'm having some serious inception issues, dream within a dream style.
I'm doing a multiquery to get the last 3 places a friend visited. I need to show [timestamp] from the location_post table and then [name] of the place from the page table. Hence the multiquery.
now, i get all the values when i check with print_r. However, when I try to echo it, I'm having serious issues getting into the array.
$query = array(
"theVisit"=>"SELECT page_id, timestamp
FROM location_post
WHERE author_uid=XXXXXXXX LIMIT 3",
"thePlace"=>"SELECT name
FROM page
WHERE page_id IN (SELECT page_id FROM #theVisit)
LIMIT 3"
);
$fql_url = $facebook->api(array(
'method' => 'fql.multiquery',
'queries' => $query
));
So far so good. Now I try to get into the array.
echo $fql_url[0]["name"]["fql_result_set"];
This prints just this: t
(just the letter t)
same goes for doing this:
echo $fql_url[0]["name"][0];
// Prints: t
I can't get my head around it. i've tried thousands of variations to get to the data but just can't get to it.
the fql_result_set seems like the obvious villain.
$fql_url[0]["name"]["theVisit"][0]["page_id"] etc, but it just kills everything that happens in the code after that.
below is the array I get from print_r
Array (
[0] => Array (
[name] => theVisit [fql_result_set] => Array (
[0] => Array (
[page_id] => 6205957466
[timestamp] => 1349138499
)
)
)
[1] => Array (
[name] => thePlace [fql_result_set] => Array (
[0] => Array (
[name] => Best Buy Theater
)
)
)
)
Well I was a bit retarded.
[fql_result_set] is obviously not nested inside ["theVisit"], which I stupidly thought.
I realized this and can easily echo what I need like this
echo $fql_url[0]["fql_result_set"][0]["name"];
this prints the correct page_id (6205957466)

PDO fetchAll array to one dimensional

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

Categories