Array in array with PHP PDO fetch modes - php

Here is an extract of my PHP code:
A function that prints the query result from a PostgreSQL database:
function getOuvrage(){
$conn = PostgreConnection::getInstance();
$sth = $conn->prepare("SELECT * FROM ouvrage WHERE code = '01'");
$sth->execute();
$result = $sth->fetchAll();
print_r($result);
}
Result SQL query in pgAdminIII is:
code |forage | station | reserve
---------+--------+-----------+----------
01 | 2 | 12 | 87
Result of print_r() function is:
Array([0] => Array ([forage] => 2 [0] => 2 [station] => 12 [1] => 12 [reserve] => 87 [2] => 87))
My questions: why are there 2 arrays and how can I get a simple array like this:
Array([forage] => 2 [station] => 12 [reserve] => 87)
EDIT :
I tried this:
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
I still get the 2 arrays:
Array([0] => Array([forage] => 2 [station] => 12 [reserve] => 87))
I tried this:
$result = $sth->fetchAll(PDO::FETCH_KEY_PAIR);
I get this:
Array()
I couldn't find an answer to my question, including in the « duplicated » question pointed by #Your Common Sense!

The solution is:
$result = $sth->fetch(PDO::FETCH_ASSOC);

Related

PHP Like System / 'Most Liked' (Need for logic)

I'am trying create a basic comment system, I was success but I have a problem right now.
I can't list "most liked" comments and I don't have an idea about how can I.
My votes database showing like that:
voteid | value | entryid | userid
25 | like | 257 | 17
24 | like | 257 | 17
23 | unlike | 257 | 18
I create a new like with this code:
$vote = $connect->prepare("INSERT INTO votes (entryid, userid, value) VALUES (:entryid, :userid, :value)");
$vote->bindParam(':entryid', $entryid);
$vote->bindParam(':userid', $userid);
$vote->bindParam(':value', $value);
$vote->execute();
And my question.
What's my need SQL Query?
I've tried like this:
$bestliked = $connect->prepare("SELECT * FROM votes");
$best = $bestliked->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_COLUMN, 2);
But I can't list the array which have most subarray. It only seems that;
[1] => Array
(
[0] => 8
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 9
[8] => 10
[9] => 11
[10] => 12
[11] => 13
[12] => 14
[13] => 15
)
[2] => Array
(
[0] => 16
)
[3] => Array
(
[0] => 17
)
Thanks All!
You could try to sum the group count and sort it descending:
Select *,count(*) as sum group by entryid where value='like' order by sum desc

mysql - delete sql row where data not match with data in array

Please can I have some help on this. I'm trying to delete SQL row in a table that are not match the data in an array.
SQL Table:
| id | Name | No
------------------
| 1 | john | 14
| 2 | rui | 156
| 3 | ted | 148
| 4 | alex | 123
| 5 | depay | 56
Array:
Array
(
[0] => Array
(
[name] => john
[no] => 14
)
[1] => Array
(
[name] => ted
[no] => 148
)
[2] => Array
(
[name] => depay
[no] => 56
)
)
This may help you
[akshay#localhost tmp]$ cat test.php
<?php
$array = array (
array (
'name' => 'john',
'no' => '14'
),
array (
'name' => 'ted',
'no' => '148'
),
array (
'name' => 'depay',
'no' => '56'
)
);
$table = "some_table";
$sql = "DELETE FROM ".$table." WHERE (NAME,NO) NOT IN (". implode(",",array_map(function($_){ return sprintf("('%s',%d)",$_['name'],$_['no']);},$array)).")";
print $sql."\n";
?>
Output
[akshay#localhost tmp]$ php test.php
DELETE FROM some_table WHERE (NAME,NO) NOT IN (('john',14),('ted',148),('depay',56))
It would be much easier if you can return "id" aka primary key of the table as array. In that case you can just grab those ids and during delete operation exclude those from the equation.
$selectQ = 'select id from table_name'; // and no>10
$result = mysql_result($selectQ);
$ids = array();
while ($info = mysql_fetch_assoc($result)) {
$ids[] = $info['id'];
}
if($ids) {
$deleteQ = 'delete from table_name where id not in ('.implode(",", array_values($ids)).')';
mysql_query($deleteQ);
}
P.S : During select query make sure to include logic for finding those users. For example, who's "no" is greater than X.Otherwise this query in default will return all ids and eventually nothing will be deleted.

php (PDO) simple way to turn rows in lookup table into simple array

given a very simple table structure thus:
mysql> describe songpart;
+----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+----------------+
| id | int(11) | NO | MUL | NULL | auto_increment |
| partName | text | NO | | NULL | |
+----------+---------+------+-----+---------+----------------+
which results in an array like this in php (when queried)
Array ( [0] => Array ( [id] => 1 [0] => 1 [partName] => Lead Guitar [1] => Lead Guitar )
[1] => Array ( [id] => 2 [0] => 2 [partName] => Bass Guitar [1] => Bass Guitar )
[2] => Array ( [id] => 3 [0] => 3 [partName] => Drums [1] => Drums )
[3] => Array ( [id] => 4 [0] => 4 [partName] => Keyboard [1] => Keyboard ) )
Am I missing some simple trick to turn this into a simple array with id as the key like so:
Array ( [1] => Lead Guitar
[2] => Bass Guitar
[3] => Drums
[4] => Keyboard )
or is it possible to get PDO to deliver an array like this?
TiA
You can simply use the PDO::FETCH_KEY_PAIR is you have only 2 columns in your result.
You can also use the PDO::FETCH_GROUP and PDO::FETCH_ASSOC together if you have more. Example :
$result = $db->query('select * from channels')->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
This will yield an array indexed with the first column containing at each index an array of the result for this key. You can fix this by using array_map('reset', $result) to get your goal.
Example :
$result = array_map('reset', $db->query('select * from channels')->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC));
Try this:
$records = $pdo->query('SELECT id, partName FROM myTable');
$records->setFetchMode(PDO::FETCH_KEY_PAIR);
print_r($records->fetchAll());
For that you need to set only your desired fields in iteration.
$part_name = [];
$records = $pdo->query('SELECT * FROM your_table');
foreach ($records as $row) {
$part_name[$row['id']] = $row['partName'];
}

Merge multiple arrays (objects) and compare to another array

My Problem
Trying to create similar arrays so I can compare them.
I am creating a distribution list for files, the adding of the distribution list work fine, I list user surname, user forename and user department, these are selected and posted, foreach user I retrieve the users.user_id and store this in a distribution table (under distro_lis)t like so.
distro_id (AI, PK) | distro_list | policy_id
---------------------------------------------
1 | 1 23 21 34 | 13
2 | 10 22 21 34 | 15
3 | 1 27 26 40 | 34
Now I working on the editing of the distribution list, so for a row, lets say row 1, I fetch the distro_list and parse it to get each user ID (from distro_list) using.
$policyID is received in the method argument
$db = $this->dbh->prepare('SELECT distro_list FROM distro WHERE policy_id = :policy_id');
$db->bindParam(':policy_id', $policyID);
$db->execute();
$row = $db->fetch(PDO::FETCH_ASSOC);
$ids = explode(' ',$row);
foreach ($ids as $user) {
$db = $this->dbh->prepare('SELECT user_forename, user_surname, user_dept FROM users WHERE user_id = :user_id ORDER BY user_surname ASC');
$db->bindParam(':user_id', $user);
$db->execute();
$row = $db->fetch(PDO::FETCH_ASSOC);
var_dump($row);
}
the var_dump($row) returns an array of arrays (objects.. not sure of the terminology here) which looks like so (print_r).
Array
(
[user_forename] => fname1
[user_surname] => sname1
[user_dept] => dept1
)
Array
(
[user_forename] => fname2
[user_surname] => sname2
[user_dept] => dept2
)
Array
(
[user_forename] => fname3
[user_surname] => sname3
[user_dept] => dept3
)
the array that I want to compare it to looks like so (print_r).
array
(
[0] => Array
(
[user_forename] => fname1
[user_surname] => sname1
[user_dept] => dept1
)
[1] => Array
(
[user_forename] => fname2
[user_surname] => sname2
[user_dept] => dept2
)
[2] => Array
(
[user_forename] => fname3
[user_surname] => sname3
[user_dept] => dept3
)
)
I understand why the first array looks like that, because im var_dump'ing' after each iteration. How can I get the first array (array of arrays or objects) into a single array so I can compare it to the second array?
Try this
$list_users = array()
foreach ($ids as $user) {
//...
$list_users[] = $row;
}
var_dump($list_users);

unable to merge variables with array_merge: undefined index

I am trying to combine two variables that retrieves information from MySQL.
I have been suggested to use array_merge(), and it seems to work for the most part. I keep getting Warning: Illegal string offset after all the results has been returned from the database. Interesting is that the first 8 (the query has a LIMIT of 8) are error clean, after the 8 results has been printed, then a huge list appears with that error.
query
articleClass.php
public function latestArticles()
{
$sth = $this->db->prepare("SELECT * FROM articles
WHERE article_uid = article_uid
ORDER BY article_uid DESC LIMIT 8");
$sth->execute();
$row = $sth->fetchAll();
return $row;
}
public function articleTags()
{
$sth = $this->db->prepare("SELECT a.*, b.*
FROM articles a, article_tags b
WHERE b.tag_id = a.article_uid
");
$sth->execute();
$row = $sth->fetchAll();
return $row;
}
printing code
index.php
include 'libraries/articleClass/articleClass.php';
$articleClass = new articleClass();
$latestArticles = $articleClass->latestArticles();
$articleTags = $articleClass->articleTags();
foreach(array_merge($latestArticles, $articleTags) as $data)
{
$first_uid = $data['article_uid'];
$first_image = $data['article_image'];
$first_title = $data['article_title'];
$first_content = $data['article_content'];
$first_created = gmdate("d M Y", $data['article_created']);
$first_tags = $data['tag_name'];
echo '
<article>
<img src="path-to-image/'.$first_image.'"/>
<h1>'.$first_title.'</h1>
<p>'.$first_content.'</p>
<ul>
<li>'.$first_tags.'</li>
</ul>
</article>
';
}
Once index.php is loaded, 8 articles are printed on the page as they should, but I get :
Notice: Undefined index: tag_name in /var/www/new-design/index.php on line 74
Trial & (mostly) Failures
If I change public function article_tags to Fetch instead of FetchAll I get these errors:
Warning: array_merge(): Argument #2 is not an array in /var/www/new-design/index.php on line 67
Warning: Invalid argument supplied for foreach() in /var/www/new-design/index.php on line 67
I am unable to figure out how to succeed with this, any leads would be great. I've been at it since morning!
UPDATE
article_tags table
+--------------------------------+
| tag_id | article_id | tag_name |
+--------------------------------+
| 1 | 8 | awesome |
| 2 | 8 | sweet |
| 3 | 8 | gross |
+--------------------------------+
there is only one article_id corresponding to the articles that are being called, yet this article still receives undefined index: tag_name of course because in the array_merge they haven't been merged at all.
What happens here is that
array_merge($latestArticles, $articleTags)
simply appends one array to the other, meaning:
The first 8 entries in the resulting array are your articles (these have the "tag_name" field set).
The rest is filled with the contents of $articleTags (those don't have "tag_name" field - causing your error).
Here's some code to illustrate that (Indices 0 to 2 are your articles while 3 to 5 are your tags, notice how indices 3-5 of the resulting array don't have the tag_name field):
$latestArticles = array(
array("article_title" => "Some Title 1", "tag_name" => "SomeTag"),
array("article_title" => "Some Title 2", "tag_name" => "SomeOtherTag"),
array("article_title" => "Some Title 3", "tag_name" => "SomeTag"),
);
$articleTags = array(
array("name" => "SomeTag", "somefield" => "foo", "otherfield" => "bar"),
array("name" => "SomeTagOtherTag", "somefield" => "baz", "otherfield" => "test"),
array("name" => "YetAnotherTag", "somefield" => "test2", "otherfield" => "test3")
);
$result = array_merge($latestArticles, $articleTags);
print_r($result);
/** Resulting Array:
Array
(
[0] => Array
(
[article_title] => Some Title 1
[tag_name] => SomeTag
)
[1] => Array
(
[article_title] => Some Title 2
[tag_name] => SomeOtherTag
)
[2] => Array
(
[article_title] => Some Title 3
[tag_name] => SomeTag
)
[3] => Array
(
[name] => SomeTag
[somefield] => foo
[otherfield] => bar
)
[4] => Array
(
[name] => SomeTagOtherTag
[somefield] => baz
[otherfield] => test
)
[5] => Array
(
[name] => YetAnotherTag
[somefield] => test2
[otherfield] => test3
)
)
*/

Categories