Getting output from a query with an implode function in it - php

I'm trying to determine whether a combination of topics related to a forum is unique. This is done while adding topics to a forum. The uniqueness is checked with this code and query:
$options = array(); //here's your choices
$options[] = 'blablabla';
$options[] = 'blabla';
foreach($options as $key => $value)
{
echo '<li>' . $value . '</li>';
}
$sql_unique = "SELECT Forums_ForumID, list
FROM (
SELECT Forums_ForumID, GROUP_CONCAT( Topics_TopicID ) AS list
FROM (
SELECT *
FROM Topics_crosstable
ORDER BY Topics_TopicID
)H
GROUP BY Forums_ForumID
)A
WHERE list = (
SELECT GROUP_concat( TopicID )
FROM Topics
WHERE Name IN (";
$sql_unique .= implode(",",$options);
$sql_unique .= ") ORDER BY Forums_ForumID ASC )";
$result = mysql_query($sql_unique);
//print "$result";
//echo $result;
//echo mysql_num_rows($result);
//$assoc = mysql_fetch_assoc($result);
var_dump($result);
I'm sure the query works fine when using fixed values in WHERE. With the current code I can't get any output. The vardump gives a result 'false' no matter if the combination of topics is unique or not. I've been trying for days now, so I really help you can help me out!
Thanks in advance!

You have to quote your options if they are strings.
$sql_unique .= "'". implode("','", $options) ."'";

Related

Execute an SQL query inside another SQL query

Ok, I assume that the title is not the best title, but let me explain my problem: I'm creating a website that needs to show posts of people (anyway), and I have to show their gravatar's profile picture, so this what I did:
<?php
function get_gravatar( $email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array() ) {
$url = 'https://www.gravatar.com/avatar/';
$url .= md5( strtolower( trim( $email ) ) );
$url .= "?s=$s&d=$d&r=$r";
if ( $img ) {
$url = '<img src="' . $url . '"';
foreach ( $atts as $key => $val )
$url .= ' ' . $key . '="' . $val . '"';
$url .= ' />';
}
return $url;
}
require("db.php");
$sql = "SELECT * FROM posts ORDER BY date DESC";
foreach ($db->query($sql) as $row) {
// var_dump($row);
$user = $row['user_id'];
$sql_user = "SELECT email FROM users WHERE id = $user";
foreach ($db->$sql_user as $row_user) {
var_dump($row_user);
echo "<img src=\"".get_gravatar($row_user['email'])."\"/>";
}
echo "<h2>".$row['title']."</h2><br/>";
echo "<p>".$row['content']."</p><br/>";
}
But, it doesn't work (well, it works, but it doesn't shows me the profile picture of the user, only the post).
So, I think the problem is that I can't call 2 times the variable $db at the same time, but I'm not sure, so that's m=why I'm asking if there is a way to fix my problem or to select 2 tables at the same time.
you can short your logic
$sql="SELECT u.email "
. "FROM posts AS p "
. "LEFT JOIN users AS u "
. "ON u.id=p.user_id "
. "ORDER BY p.date DESC";
use join
SELECT * FROM users join posts on users.id =Posts.user_id ORDER BY date DESC
you don't apply query to sql string in second foreach
foreach ($db->query($sql_user) as $row_user) {
see your second foreach you miss to put query function
foreach ($db->query($sql) as $row) {
foreach ($db->query($sql_user) as $row_user) {
You could just use JOIN
JOIN clause is used to combine rows from two or more tables, based on
a related column between them.

PHP: How to pass multiple values to SELECT query

I am new to PHP and hope someone can help me with this.
I currently use the below lines to retrieve a value from a db and to output it as an array with the item's ID and value which works as intended.
Now I would need to do the same for multiple items so my input ($tID) would be an array containing several IDs instead of just a single ID and I would need the query to do an OR search for each of these IDs.
I was thinking of using a foreach loop for this to append " OR " to each of the IDs but am not sure if this is the right way to go - I know the below is not working, just wanted to show my thoughts here.
Can someone help me with this and tell me how to best approach this ?
My current PHP:
$content = "";
$languageFrm = $_POST["languageFrm"];
$tID = $_POST["tID"];
$stmt = $conn->prepare("SELECT tID, " . $languageFrm . " FROM TranslationsMain WHERE tID = ? ORDER BY sortOrder, " . $languageFrm);
$stmt->bind_param("s", $tID);
$stmt->execute();
$result = $stmt->get_result();
while($arr = $result->fetch_assoc()){
$content[] = array("ID" => $arr["tID"], "translation" => $arr[$languageFrm]);
}
My thought:
foreach($tID as $ID){
$ID . " OR ";
}
Many thanks for any help,
Mike
There are two approaches, assuming $tID is an array of IDs
Using MySQL IN() clause
This will work also when $tID is not an array, but a single scalar value.
$tID = array_map('intval', (array)$tID); // prevent SQLInjection
if(!empty($tID)) {
$query .= ' WHERE tID IN(' . implode(',', $tId) . ')';
} else {
$query .= ' WHERE 0 = 1';
}
Using OR clause, as you suggested
A bit more complicated scenario.
$conds = array();
foreach($tID as $ID) {
$conds[] = 'tID = ' . intval($ID);
}
if(!empty($conds)) {
$query .= ' WHERE (' . implode(' OR ', $conds) . ')';
} else {
$query .= ' WHERE 0 = 1';
}
As per above conditions you can try with implode();
implode($tID,' OR ');
You can also use IN condition instead of OR something like this.
implode($tID,' , ');

PHP MySQL check if items in array exist in Table, THEN SHOW

PHP 5.4 with MySQL
Building off of this:
<?php
$arr = ...
$sql = 'SELECT COUNT(*) FROM table WHERE field IN ( ' . implode( ',', $arr ) . ' );';
$result = $db->query( $sql );
?>
How would I display which items of the array ARE NOT in the table?
Instead of returning the count, return the field itself:
$sql = 'SELECT field WHERE field IN ' . implode( ',', $arr ) . ' );';
$result = $db->query($sql);
$found = array();
while ($row = $result->fetch_assoc()) {
$found[] = $row['field'];
}
Then you can compare the two arrays:
$not_found = array_diff($arr, $found);
If your $arr variable is sanitized and safe to build a query with, you can use union operators to build a table containing all the words in the array, then you can left join that table to table.field and only keep array items where there was no match.
$arr = array('one','two');
$sql = "select item from (
select '" . implode("' item union select '",$arr). "' item
) t1 left join table t2 on t2.field = t1.item
where t2.field is null";
this will produce the following sql
select item from (select 'one' item union select 'two' item) t1
left join table t2 on t2.field = t1.item
where t2.field is null
Just to give an idea (this probably won't work)
$arr = ...
$sql = 'SELECT field FROM table WHERE field IN ( ' . implode( ',', $arr ) . ' );';
$result = $db->query( $sql );
while($r = $result->fetch())
$arr2[] = $r['field'];
print_r(array_diff($arr,$arr2));
after you've done imloud, array ceases to be an array, this is a string, so you do not have to select count(*). You need to select id after do the while and compare arrays
Just use "NOT IN", if your items is up to 10 elements:
<?php
$arr = array('one','two');
$filterExisting = "'" . implode("', '", $arr ) . "'";
$sql = "SELECT COUNT(*) FROM table WHERE field NOT IN (". $filterExisting .")";
$result = $db->query($sql);
?>

How to get sum of a column in Zend framework using model and controller

I am looking for a way to get the sum of a column. The query i am using looks like this:
public function gradeRound($rating)
{
$sql = mysql_query("Select SUM(rating) AS grades FROM" . $this->_prefix . "media_set_rating WHERE set_id = set_id");
mysql_real_escape_string($rating->rating);
$row = mysql_fetch_assoc($sql);
$grades = $row['grades'];
}
I am not sure how to get this properly formatted for the controller. right now my controller has this.
i put a text box on the page and echoed $grades - this is also included in the view as so:
$this->_view->assign('grades', $grades);
so that i can use it.
I tried replacing $setId with $rating both of which are being requested at the top.
I do not get anything out of my echo. I had -1 in there earlier. i am not sure where it was getting that from. I was trying different methods and got different results.
appreciate any hints or clues as to how to do this.
thanks
Revised 2:17 EST May 27 2013
Thanks Niko. I must be getting tired!
Here is the revised query:
public function gradeRound($rating)
{
$sql = sprintf("Select SUM(rating) AS grades FROM " . $this->_prefix . "media_set_rating
WHERE set_id = set_id");
$sum = mysql_query($sql);
$row = mysql_fetch_assoc($sum);
$grades = $row['grades'];
return $grades;
}
$grades = $setDao->gradeRound($setId);
Your SQL query looks rather odd. Depending on the type of "set_id", it is supposed to look like this:
mysql_query("
Select SUM(rating) AS grades
FROM " . $this->_prefix . "media_set_rating
WHERE set_id = '". mysql_real_escape_string($rating->rating) ."'"
);
for ยด$rating->rating` being a string. For an integer, it should be:
mysql_query("
Select SUM(rating) AS grades
FROM " . $this->_prefix . "media_set_rating
WHERE set_id = ". (int) $rating->rating
);
And in total (adding also a return statement):
public function gradeRound($rating)
{
// expecting "set_id" to be an integer field
$result = mysql_query("Select SUM(rating) AS grades FROM " . $this->_prefix . "media_set_rating WHERE set_id = ". (int) $rating->rating);
$row = mysql_fetch_assoc($result);
return $row['grades'];
}
Hope this will help You !
$select = $table->select();
$select->from ("table", array("date", "column1" => "sum(column1)"));
$select->group ( array ("date") );

Combine a variable with SELECT results into an INSERT statement

I have 3 tables:
Users - uID (INT AUTO_INCREMENT), name (VARCHAR)
Movies - mID (IN AUTO_INCREMENT), title (VARCHAR)
Watched - uID (INT), mID (INT)
I'm writing a php function that constructs a query which adds records of movies watched by a particular person. Here's what I've come up with so far:
function set_watched($name, $movies){
$sql = "SET #userid = (SELECT uID FROM users WHERE name = '$name' LIMIT 1); ";
$sql .= "INSERT INTO watched (uID, mID) VALUES ('";
foreach ($movies as $index => $movie){
}
}
My question:
Is there a way to combine the #userid variable with the results of a SELECT mID FROM MOVIES WHERE title = $movie OR title = $movie [generated with foreach]?
I don't want to generate separate SELECT statements for every movie title. Perhaps I don't even have to use the #userid variable at all?
Try something like this:
$sql = "INSERT INTO watched (uID, mID)
SELECT User.uID, Movies.mID
FROM (SELECT uID FROM Users WHERE Users.name = '$name' LIMIT 1) AS User, Movies
WHERE ";
foreach ($movies as $index => $movie){
$sql .= "Movies.title = '$movie' OR ";
}
$sql = substr($sql, 0, -4) . ";";
I prefer using arrays and imploding them for this sort of an application. Also, I wouldn't try and force these two things into one query. I would either:
Modify the function parameters to accept uID as its input, instead of name
Change the logic to two queries.
Besides, PHP's mysql_query function doesn't support multiple queries, so if you're using the standard mysql functions, you can't execute two queries with one call to mysql_query.
Running with case #2, you can use something like this (untested, of course):
$sql = 'SELECT uID FROM users WHERE name = "' . $name. '" LIMIT 1';
$result = mysql_query( $sql);
$row = mysql_fetch_row( $result);
mysql_free_result( $result);
$values_array = array();
foreach ($movies as $index => $movie)
{
$values_array[] = '( "' . $row['uID'] . '", "' . $movie . '")';
}
$sql = 'INSERT INTO watched (uID, mID) VALUES ' . implode( ', ', $values_array);
$result = mysql_query( $sql);

Categories