PHP: output count() - php

How do i work with the COUNT()
$sql = $connect->prepare("SELECT COUNT() FROM discos_events e INNER JOIN discos_events_guests eg ON (e.ID = eg.eID) INNER JOIN users u ON (eg.uID = u.id) WHERE e.dID =:id");
$sql->bindValue(":id", $cID);
$sql->execute();
...then what? echo $sql["count"]; ? to output the count?

You need an alias name for your COUNT() column:
$sql = $connect->prepare("SELECT COUNT() AS num_events FROM discos_events e INNER JOIN discos_events_guests eg ON (e.ID = eg.eID) INNER JOIN users u ON (eg.uID = u.id) WHERE e.dID =:id");
$sql->bindValue(":id", $cID);
// Fetch the results and then access the alias
$sql->execute();
$result = $sql->fetch();
echo $result['num_events'];

you need to execute() the query, so:
$result = $sql->execute(array('id' => $cId)); // just to illustrate that you can use this instead of bindParam
if ($result) {
$row = $sql->fetch();
}

after execute, you have to store_result() and fetch()
As #Michael suggests, you may alias the count(), to get it in more reatable form.

Your query needs to assign the count value to a name, like so:
SELECT COUNT() n FROM discos_events ...
Then you can reference the name n in your PHP array:
echo $sql["n"];
You can, of course, call it 'count' or any other name you prefer, but be careful of using names which are reserved words in SQL (such as 'count'). If you want to give it a reserved name, you need to enclose it in backtick characters so that SQL recognises that it's a name you want to use rather than its own reserved word.

Related

PHP PDO: Can't bind value to multiple variables?

I am trying to execute a query that joins several tables using the same foreign key via the below query but it returns false.
$question_id = 11406;
$query = $db->prepare("SELECT q.question_attempts_permitted, q.question_range, a.answer_text, r.attempt_count
FROM checkup_questions q, checkup_answers a, user_responses r
WHERE a.question_id=:question_id AND q.question_id=:question_id AND r.question_id=:question_id");
$query->bindValue(':question_id', $question_id, PDO::PARAM_INT);
$query->execute();
However, if I inject the question_id directly the query returns the desired result.
$query = $db->prepare("SELECT q.question_attempts_permitted, q.question_range, a.answer_text, r.attempt_count
FROM checkup_questions q, checkup_answers a, user_responses r
WHERE a.question_id=11406 AND q.question_id=11406 AND r.question_id=11406");
$query->execute();
Is there some limitation with the bindValue interface that causes the first query to fail while the second one returns as expected?
Query text should be rewritten using JOIN:
$query = $db->prepare("
SELECT q.question_attempts_permitted, q.question_range, a.answer_text, r.attempt_count
FROM checkup_questions q
JOIN checkup_answers a ON a.question_id = q.question_id
JOIN user_responses r ON r.question_id = q.question_id
WHERE q.question_id=:question_id
");
// you can provide placeholder without `:`
$query->bindValue('question_id', $question_id, PDO::PARAM_INT);
$query->execute();
Here you have only one placeholder.

PHP search box issuse

I have a problem with some php code. So, when I write some text inside search box I should get more results, but I only get 1. This happened to my when I added second query with INNER JOIN. I have no idea why I'm getting only 1 result instead of more, anyone can help?
When I remove second query, it shows me all results.
$STH = $DBH->prepare('SELECT * FROM tv_shows WHERE title like :q ORDER BY title ASC LIMIT 5');
$STH->setFetchMode(PDO::FETCH_OBJ);
$STH->execute(array(
':q' => "%$q%"
));
if($STH->rowCount()) {
while($row = $STH->fetch()) {
$poster = $row->poster;
$mtitle = $row->title;
$mrd = $row->release_date;
$mid = $row->id;
$genres = "";
$STH = $DBH->prepare('SELECT g.title from genres g INNER JOIN tv_show_genres tg ON g.id = tg.genre_id INNER JOIN tv_shows t ON t.id = tg.tv_show_id WHERE t.id = :tid');
$STH->setFetchMode(PDO::FETCH_OBJ);
$STH->execute(array(
':tid' => $mid
));
if($STH->rowCount()) {
while($row = $STH->fetch()) {
$genres .= $row->title.", ";
}
echo
'<li>
<span class="search-poster"><img src="'.$poster.'"></span>
<span class="search-title">'.$mtitle.' ('.$mrd.')</span>
<span class="search-genre">'.substr($genres,0,-2).'</span>
</li>';
}
}
}
You're using the same variable $STH for both queries. So when the outer loop gets back to the
while ($row = $STH->fetch())
line, $STH now refers to the second query. Since you've reached the end of the results from that query, calling fetch() here returns false, so this loop ends as well.
Just use different variable names, e.g. $show_STH and $genre_STH.
However, an even better solution is to use a single query.
SELECT s.poster, s.title AS show_title, s.release_date, g.title AS genre_title
FROM (SELECT *
FROM tv_shows
WHERE title like :q
ORDER BY title ASC
LIMIT 5) AS s
INNER JOIN tv_show_genres tg ON s.id = tg.tv_show_id
INNER JOIN genres g ON tg.genre_id = g.id
ORDER BY s.title
Most of the time when you find yourself performing queries in nested loops like this, you can replace it with a single query that joins the two queries.

Why is my sql count printing alphabetical text?

$users = mysql_query("SELECT *, COUNT(votes.id) FROM users INNER JOIN votes
ON users.id=votes.recipientuserid WHERE votes.datenumber >='2014' ");
while($user = mysql_fetch_array($users)){
$count = $user[COUNT(votes.id)];
}
In phpmyadmin the query count displays a number. The value of $count is not a number but the users.username value. Why?
One way to accomplish what you want is to modify your query by adding a field name to count so that you can access it as any other field in the results:
SELECT *, COUNT(votes.id) as nbvotes FROM users ...
And the from php once you have the results, you can access it this way
$row['nbvotes']
where $row is the variable containing the record returned from mysql. Do not forget the appostrophes.
Cheers
$users = mysql_query("SELECT COUNT(votes.id) as count FROM users INNER JOIN votes
ON users.id=votes.recipientuserid WHERE votes.datenumber >='2014' ");
while($user = mysql_fetch_array($users)){
$count = $user['count'];
}

php mysql select something and get columns from other tables

I'm using prepared statements and I need to "select" other table, apart from these two, to get data but I get this:
Fatal error: Call to a member function bind_param() on a non-object in C:\xampp\htdocs\views\user\referral.php on line 16
If I add in SELECT table1.* , table.* , "theothertable.*"
$stmt = $mysqli->prepare("SELECT friends.*, rc_usuario.* // or just *
FROM friends
INNER JOIN rc_usuario ON rc_usuario.id = friends.friendID
WHERE friends.userID = ?");
$stmt->bind_param('s', $connectedUserID);
This is working fine, I get what i need, but I also need to get data from another table and I can't make other select because i need it all in a while to print all the data together.
The question is, can I SELECT something like that from 2 tables and also get data from other table/s?
Thank YOU!
EDIT: Add the new statement:
if ($stmt = $mysqli->prepare("SELECT friends.*, members.*, account_type.*
FROM friends
INNER JOIN members ON members.id = friends.friendID
INNER JOIN account_type ON account_type.name = members.acc_type
WHERE friends.userID = ? AND members.acc_type = ?")) {
$stmt->bind_param('is', $connectedUserID, $connectedAcc_type);
$stmt->execute();
} else echo $mysqli->error;
You can join more tables by using another INNER JOIN, like as follows;
INNER JOIN rc_usuario ON rc_usuario.id = friends.friendID
INNER JOIN rc_another ON rc_another.col = friends.coljoin
Just make sure you select all the columns you want in the joined table.
It might also help to run your prepare statement in an if, like this;
if($stmt = $mysqli->prepare("SELECT ...")) { // ... where the rest of your query is
$stmt->bind_param('s', $connectedUserID);
$stmt->execute();
}
else {
echo $mysqli->error;
}
which will give you an idea of any problems with the SQL syntax.
Hope this helps.

How do I retrieve a single column from mysqli results

This is my code:
<?php
$con=mysqli_connect("localhost","user","password","database");
$post_id = '5';
$query= mysqli_query($con,"select t.tag_name from tag_map tm join article p on p.post_id = tm.post_id join tag t on t.tag_id = tm.tag_id where p.post_id = '$post_id'");
while($que = mysqli_fetch_row($query))
{
echo "<pre>";
print_r($que);
}
?>
This is output I got:
Array
(
[0] => audit
)
Array
(
[0] => income tax
)
The output is not exactly what I want. I need exactly only the values like audit, income tax only. Can any one help me?
Needed Output :
audit
income tax
If you just want to get the result as an assoc array and don't want to use bind_param etc. you could just use php function array_column with the specific column name on your result:
$result = array_column($connection->query('SELECT xy FROM table')->fetch_all(MYSQLI_ASSOC), 'xy');
For starters, you should be using prepared statements to avoid SQL injection. After that, you can use either mysqli::bind_result OR mysqli_stmt::get_result and mysqli_result::fetch_array. I'll demonstrate both methods here.
It is important to take these practices on board, you are using mysqli instead of mysql, so it makes sense to avail yourself of the enhanced features this library brings to bear.
First, preparing a statement:
// initiate database connection
$db = mysqli_connect(
"localhost",
"user",
"password",
"database"
);
// set up your statement with ? parameters
$statment = $db->prepare('
SELECT
t.tag_name
FROM
tag_map tm
JOIN
article p ON
p.post_id = tm.post_id
JOIN
tag t ON
t.tag_id = tm.tag_id
WHERE
p.post_id = ?
');
// bind values for each parameter
$statement->bind_param('i', $post_id);
// execute the statement
$statement->execute();
The code above will safely prepare the query and fire it at the database, you've got some results to work with now. As mentioned, you can use two different methods. First is bind_result, as follows:
// list the columns you want to get from each row as variables
$statement->bind_result($tagName);
// then loop the results and output the columns you bound above
while($statement->fetch()){
echo $tagName.'<br>';
}
The second method is to use get_result, then loop those results and use fetch_array to grab an associative array, from which you can get the column you're after, as follows:
$result = $statement->get_result();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
echo $row['tag_name'].'<br>';
}
... in either case, use free_result when you're done.
$statement->free_result();
Documentation
mysqli::prepare - http://www.php.net/manual/en/mysqli.prepare.php
mysqli_stmt::get_result - http://www.php.net/manual/en/mysqli-stmt.get-result.php
mysqli_stmt::bind_param - http://www.php.net/manual/en/mysqli-stmt.bind-param.php
mysqli_stmt::bind_execute - http://www.php.net/manual/en/mysqli-stmt.execute.php
mysqli_stmt::bind_result - http://www.php.net/manual/en/mysqli-stmt.bind-result.php
mysqli_stmt::fetch - http://www.php.net/manual/en/mysqli-stmt.fetch.php
mysqli_result::fetch_array - http://www.php.net/manual/en/mysqli-result.fetch-array.php
Try this,
<?php
while($que = mysqli_fetch_row($query))
{
echo "<pre>";
echo $que[0];
}
?>
<?php
$con=mysqli_connect("localhost","user","password","database");
$post_id = '5';
$query= mysqli_query($con,"select t.tag_name from tag_map tm join article p on p.post_id = tm.post_id join tag t on t.tag_id = tm.tag_id where p.post_id = '$post_id'");
while($que = mysqli_fetch_row($query))
{
echo $que[0];
}
?>
Try with $que[0]:
while($que = mysqli_fetch_row($query))
{
echo "<pre>";
print_r($que[0]);
}

Categories