mySQL select with conditions replyTo - php

I know how to retrieve the comments for each posts, but now I'm trying to do my own system 'reply to'. When someone replying, I store the comment id as reply_id in new comment.
$sql = 'SELECT cid, cname, user_uid, reply_id,
published, content, avatar
FROM comments, users
WHERE report < 3 AND (uid = user_uid AND post_pid='.$id.')
OR ( user_uid ="_'.$id.'" AND post_pid='.$id.')';
this request return me this list of comments:
Array
(
[0] => stdClass Object
(
[cid] => 101
[cname] => ramzan
[user_uid] => 1
[reply_id] => 100
[published] => 2013-12-08 01:44:56
[content] => why?
[avatar] => users/anonyme.png
)
[1] => stdClass Object
...
but I want to get something like this :
Array
(
[0] => stdClass Object
(
[cid] => 101
[cname] => ramzan
[user_uid] => 1
[reply_id] => array() // the reply if exist
[published] => 2013-12-08 01:44:56
[content] => why?
[avatar] => users/anonyme.png
)
maybe this is a bad idea to do like this, but I don't know how to do otherwise!!!

maybe someone can help this, I resolved my problem like this :
lvl1, lvl2 have to be declare as null, only set the value of field when someone reply to a comment
...SELECT field FROM table where ...
ORDER BY COALESCE (lvl1, lvl2, id ), lvl1, lvl2, id
...
Thank you,
Best regards

Related

Get the highest value of array query mysql, php

With a big Thanks to others here i get this query now. its working fine, but i would need to get just the highest value of the post_id (how_many). it seems not possible to set a MAX(count(*)) on that. so how could i change this to get only the highest count by every id? i just need the value of every id where count == highest. how could i do this? thanks for any help.
$test = $wpdb->get_results('select
posts_id, value,count(*) as how_many
From wp_mrp_rating_item_entry_value
group by
posts_id, value
order by count(*) desc');
echo '<pre>';
print_r($test);
echo '</pre>';
i would need something like order by MAX((count(*)) or MAX((count(how_many))
i already read this but i dont know how to use this for my purpose Filtering log file using COUNT, GROUP BY, ORDER BY MAX
this is an example of the output i get now. so number 1 should not appear because number [0] has been voted 2 times. (how_many). i just need every id 1x in the output. no id shouldt appear twice or more. cause just the highest count is needed. thanks and sorry for the bad english.
Array
(
[0] => stdClass Object
(
[posts_id] => 336
[value] => 8
[how_many] => 2
)
[1] => stdClass Object
(
[posts_id] => 336
[value] => 7
[how_many] => 1
)
[2] => stdClass Object
(
[posts_id] => 380
[value] => 5
[how_many] => 1
)
[3] => stdClass Object
(
[posts_id] => 378
[value] => 7
[how_many] => 1
)
[4] => stdClass Object
(
[posts_id] => 329
[value] => 2
[how_many] => 1
)
[5] => stdClass Object
(
[posts_id] => 327
[value] => 3
[how_many] => 1
)
)
You can filter the resulting groups in a HAVING clause based on a match against a subquery for the maximal count:
SELECT posts_id, value, COUNT(*) AS how_many
FROM wp_mrp_rating_item_entry_value t1
GROUP BY posts_id, value
HAVING how_many = (
SELECT COUNT(*)
FROM wp_mrp_rating_item_entry_value t2
WHERE t2.posts_id = t1.posts_id
GROUP BY t2.value
ORDER BY COUNT(*) DESC
LIMIT 1
)

do a select on two tables and the result allows access to fields of these two selected tables

Im doing a search system and Im having some problems.
I need to search in two tables (news and pages), I already had sucess doing my search system for just one table, but for two tables its not easy to do.
I already use a select statment with two tables using UNION because I want to show number of search results, that is number of returned rows of my first sql statment.
But now I need to do a select statment that allows me to acess all fields of my news table and all fields of my pages table.
I need to acess in my news table this fields: id, title, content, link, date, nViews
I need to acess in my pages table this fields: id, title, content, link
Im trying to do this also with UNION, but in this case Im not having any row returning.
Do you see what I have wrong in my code?
<?php
//first I get my $search keyword
$search = $url[1];
$pdo = connecting();
//then I want to show number of returned rows for keyword searched
$readALL = $pdo->prepare("SELECT title,content FROM news WHERE title LIKE ? OR content LIKE ?
UNION SELECT title,content FROM pages WHERE title LIKE ? OR content like ?");
$readALL->bindValue(1,"%$search%", PDO::PARAM_STR);
$readALL->bindValue(2,"%$search%", PDO::PARAM_STR);
$readALL->bindValue(3,"%$search%", PDO::PARAM_STR);
$readALL->bindValue(4,"%$search%", PDO::PARAM_STR);
$readALL->execute();
//I show number of returned rows
echo '<p>Your search keyword returned <strong>'.$readALL->rowCount().'</strong> results!</p>';
//If dont return any rows I show a error message
if($readALL->rowCount() <=0){
echo 'Sorry but we didnt found any result for your keyword search.';
}
else{
//If return rows I want to show, if it is a page result I want to show title and link that I have in my page table
//if it is a news result I want to show title and link that I have in my news table and also date of news
echo '<ul class="searchlist">';
$readALL2 = $pdo->prepare("SELECT * FROM news WHERE status = ? AND title LIKE ? OR content LIKE ? LIMIT 0,4
UNION SELECT * FROM pages where title LIKE ? OR content LIKE ? LIMIT 0,4");
$readALL2->bindValue(1, '1');
$readALL2->bindValue(2, "%$search%", PDO::PARAM_STR);
$readALL2->bindValue(3, "%$search%", PDO::PARAM_STR);
$readALL2->bindValue(4, "%$search%", PDO::PARAM_STR);
$readALL2->execute();
while ($result = $readALL2->fetch(PDO::FETCH_ASSOC)){
echo '<li>';
echo '<img src="'.BASE.'/uploads/news/'.$result['thumb'].'"/>';
echo ''.$result['title'].'';
//if it is a news result I also want to show data on my list
//echo '<span id="date">'.$result['data'].'</span>';
echo '</li>';
}
echo ' </ul>';
//but how can I do my select statement to have access to my news table fields and my page table fields??
}
?>
This is my news table:
This is my pages table:
When I search on my form for keyword "doc" I get this:
Your are searching for keyword: "doc"
your search returned 2 results!
Array ( [id_news] => 472 [thumb] => 2014/07/title-of-news-11405372264.png [title] => Documents [content] => Link 1, Link 2 [ofte] => 2014-07-14 23:11:04 [views] => 0 [author] => 1 [category] => 116 [status] => 1 [id] => 1 [link] => documents ) image of news Documents
Array ( [id_news] => 473 [thumb] => 2014/07/title-of-news-21405372282.png [title] => Documents [content] => Link 1, Link 2 [ofte] => 2014-07-14 23:11:22 [views] => 0 [author] => 1 [category] => 115 [status] => 1 [id] => 1 [link] => documents ) image of news Documents
Array ( [id_news] => 472 [thumb] => 2014/07/title-of-news-11405372264.png [title] => About [content] => we are a company... [ofte] => 2014-07-14 23:11:04 [views] => 0 [author] => 1 [category] => 116 [status] => 1 [id] => 2 [link] => about ) image of news About
Array ( [id_news] => 473 [thumb] => 2014/07/title-of-news-21405372282.png [title] => About [content] => we are a company... [ofte] => 2014-07-14 23:11:22 [views] => 0 [author] => 1 [category] => 115 [status] => 1 [id] => 2 [link] => about ) image of news About
Array ( [id_news] => 472 [thumb] => 2014/07/title-of-news-11405372264.png [title] => Contacts [content] => Email: test#email.com [ofte] => 2014-07-14 23:11:04 [views] => 0 [author] => 1 [category] => 116 [status] => 1 [id] => 3 [link] => contacts ) image of news Contacts
Array ( [id_news] => 473 [thumb] => 2014/07/title-of-news-21405372282.png [title] => Contacts [content] => Email: test#email.com [ofte] => 2014-07-14 23:11:22 [views] => 0 [author] => 1 [category] => 115 [status] => 1 [id] => 3 [link] => contacts ) image of news Contacts
To query 2 tables, and have the result set contain columns from both tables:
SELECT n.id, n.status, n.views, p.id, p.title
FROM news n, pages p
WHERE n.status = ?
AND p.title = ?
...
To simplify my answer I have omitted most of your required columns, but you simply add more to the select statement. Of course, you can always use
SELECT n.*, p.*
To select all columns from both tables.
Update:
For your specific scenario, try:
SELECT n.*, p.*
FROM news n, pages p
WHERE n.title LIKE ?
OR n.content LIKE ?
OR p.title LIKE ?
OR p.content LIKE ?

Return a value not found in the table with MySQL?

Assuming the following array:
$users = array(
// User ID => Username
'72' => 'jack192',
'23' => 'robert1984',
'253' => 'mary111',
'4' => 'jason92'
);
and the following table:
Table myTable:
username | colFoo | colBar
I would like run a query like the following, however I would like the output to additionally include a column not in the table (The user's ID from the array):
$user_string = implode("','", array_values($users));
$query = "SELECT username, colFoo, colBar FROM myTable WHERE username IN ('$user_string')";
This would normally output something like this:
Array
(
[0] => Array
(
[username] => jack192
[colFoo] => 98
[colBar] => 7
)
[1] => Array
(
[username] => robert1984
[colFoo] =>
[colBar] => 2
)
[2] => Array
(
[username] => mary111
[colFoo] => 41
[colBar] => 9
)
[3] => Array
(
[username] => jason92
[colFoo] => 46
[colBar] => 13
)
)
However, I would like the output to look like this, with user_id corresponding to the key in the original array:
Array
(
[0] => Array
(
[username] => jack192
[colFoo] => 98
[colBar] => 7
[user_id] => 72
)
[1] => Array
(
[username] => robert1984
[colFoo] =>
[colBar] => 2
[user_id] => 23
)
[2] => Array
(
[username] => mary111
[colFoo] => 41
[colBar] => 9
[user_id] => 253
)
[3] => Array
(
[username] => jason92
[colFoo] => 46
[colBar] => 13
[user_id] => 4
)
)
I suppose I basically want to just feed the user's ID into the query and get it back out as output, without MySQL doing anything further with it. Is this possible to do purely in SQL without any additional PHP code?
Note: I do not have write access to the DB I'm pulling this data from, and I did not create the schema, so I can't add a user_id field to it or anything.
Here is another way to do it, almost a mashup of the other 2 answers. You can build a 'fake' table and JOIN it to myTable.
SELECT t.username, t.colFoo, t.colBar, s.user_id
FROM myTable t
LEFT JOIN
(
SELECT 72 as user_id, 'jack192' as username
UNION SELECT 23 as user_id, 'robert1984' as username
UNION SELECT 253 as user_id, 'mary111' as username
UNION SELECT 4 as user_id, 'jason92' as username
) s
ON t.username = s.username;
SQLFiddle example - sqlfiddle.com/#!2/64650/2
The fake table structure can be created by a php foreach loop.
$select = '';
foreach ($users as $k => $v){
$select .= "UNION SELECT $k as user_id, '$v' as username\n";
}
echo ltrim($select, "UNION ");
Still a tedious, and not ideal solution, but another option.
You might try CASE
SELECT username, colFoo, colBar,
CASE `username`
WHEN 'jack192' THEN SELECT 72;
WHEN 'robert1984' THEN SELECT 23;
ELSE SELECT NULL;
...
END CASE userid
FROM myTable ...
It will get a bit cumbersome if there are a lot of values in the array.
http://dev.mysql.com/doc/refman/5.0/en/case.html
You can't do this with SQL alone because the id is not defined in the table (not withstanding the cumbersome case statement proposed by Hulka).
Less directly answer the question but providing an alternate solution:
However, you can make a 'small' modification to your php which will accomplish the desired result:
$user_string = implode("','", array_values($users));
foreach ($users as $k => $v){
$query[$k] = "SELECT \"$v\"
,username
,colFoo
,colBar
FROM myTable WHERE username IN ('$user_string')";
}
the query is is basically the same as 'SELECT "6" as user_id, field from TABLE;' for each user, this which would return
6 field
----------
6 value1
6 value2
...
depending on your interface you may be able to prepare and execute, but you did not give enough details to produce specific code.
You would have to run the query multiple times, but you could push or array_merge. Although, I personally think you should use the user_ids as the indexes for this new array. That would require a modest rewrite of above.

Redbeanphp - Getting data from foreign key index

Sorry for the vague title, if anyone would like to edit it to reflect more about what I am posting, please do so. Here is the situation. I have 3 tables:
support:
id | contact_id | title | problem | etc
supportlogin:
id | contact_id | login | pass | etc
contact:
id | first_name | last_name | email | etc
I am loading the support bean just fine, and am accessing the contact info:
$support=R::load('support',1);
echo $support->contact->first_name;
I want to echo the supportlogin information similarly:
echo $support->contact->ownSupportlogin->login;
Is this possible, and am I doing it the right way? I have tried the following ways with no success:
echo $support->contact->supportlogin->login;
echo $support->contact->ownSupportlogin->login;
echo $support->contact->ownSupportlogin[0]->login;
EDIT: MORE INFO
I did print_r($support->contact) and was given the data:
RedBean_OODBBean Object
(
[null:RedBean_OODBBean:private] =>
[properties:RedBean_OODBBean:private] => Array
(
[id] => 109
[phone] => 1234580970
[first_name] => Tim
[last_name] => Withers
)
[__info:RedBean_OODBBean:private] => Array
(
[type] => contact
[sys.id] => id
[tainted] =>
)
[beanHelper:RedBean_OODBBean:private] => RedBean_BeanHelperFacade Object
(
)
[fetchType:RedBean_OODBBean:private] =>
)
And then I did print_r($support->contact->ownSupportlogin) and this showed up:
Array
(
[13] => RedBean_OODBBean Object
(
[null:RedBean_OODBBean:private] =>
[properties:RedBean_OODBBean:private] => Array
(
[id] => 13
[link] => fecd4ef67e8c789efa1792f9ee0efff4
[login] =>
[password] =>
[receiveemails] => 1
[contact_id] => 109
[role] => 1
)
[__info:RedBean_OODBBean:private] => Array
(
[type] => supportlogin
[sys.id] => id
[tainted] =>
)
[beanHelper:RedBean_OODBBean:private] => RedBean_BeanHelperFacade Object
(
)
[fetchType:RedBean_OODBBean:private] =>
)
)
I can access it using: echo $support->contact->ownSupportlogin[13]->login;, but doing it dynamically seems to be a problem....
Figured it out, and will leave it up in case anyone else has a similar problem:
This will only work if you have a 1:1 relationship. Redbean populates the ownSupportlogin as an array of all supportlogin rows related to the contact. If one table can have many child tables, then you will need to loop through that array and pull out the data you want. If it is a 1:1 relationship, then you can use PHP's reset() to access the data of the first element in the array:
echo reset($support->contact->ownSupporlogin)->login;

Get meta information for selected columns from PostgreSQL using PHP

is there a way of getting table name for each column in a postgre result in PHP?
Imagine you have a select with join, for example:
$Q = <<<E2OD
SELECT * FROM user U
LEFT JOIN department D ON U.department_id = D.id
E2OD;
In PHP/FirebirdSQL:
$R = ibase_query($Q);
$D = ibase_fetch_row($R);
$info = ibase_field_info($R, 0);
Returns
Array
(
[0] => id
[name] => id
[1] => id
[alias] => id
[2] => user
[relation] => user
[3] => 8
[length] => 8
[4] => BIGINT
[type] => BIGINT
)
While in PHP/PostgreSQL:
$select = $DB->query($Q);
$meta = $select->getColumnMeta(0);
Returns
Array
(
[pgsql:oid] => 20
[native_type] => int8
[name] => id
[len] => 8
[precision] => -1
[pdo_type] => 2
)
As you see, there's no information about the table the column is from. There's a missing key [relation] => user or similar displaying the table name.
http://php.net/manual/en/pdostatement.getcolumnmeta.php
Can PHP get this information with it's PG or PDO libraries? Does PostgreSQL provide this information to client libraries? What needs to be done to make this happen?
Thanks for any hint,
Michal
Check pg_field_table().

Categories