i have this code
$opslaglimit = 5;
$fag = "dansk";
$fagquery = "%".ucfirst($fag)."%";
$fagopslag = $db->prepare("
SELECT
*,
teacher_opslag.id as mainid,
teacher_opslag.created AS opslagcreated,
teacher_opslag.subject AS opslagsubject,
teacher_opslag.deleted AS maindeleted
FROM
teacher_opslag
WHERE
teacher_opslag.subject LIKE ?
ORDER BY
teacher_opslag.id DESC
LIMIT
$opslaglimit
");
$fagopslag->bind_param("s", $fagquery);
$fagopslag->execute();
$fagresult = $fagopslag->get_result();
$ensuranced = $fagresult->num_rows;
The query should select all data where dansk is present from the table. one of my rows might look like this Dansk_Engelsk_Svensk. The num_rows returns 0.
It is the first time i use LIKE in a WHERE clause. I dont know why it returns 0 when i have 3 matching rows in the db.
please help, thanks
Related
I am developing a voting system and am experiencing an incompatibility problem between the SELECT AVG function and mysqli_num_rows.
When using AVG(), mysqli_num_rows always returns the number 1. However, I need the real number of rows for my if statement. How can I do that?
$consulta_nota_geral = "SELECT * , avg(comp1) as competencia1 , avg(comp2) as competencia2 , avg(comp3) as competencia3 , avg(comp4) as competencia4 , avg(comp5) as competencia5 FROM votos WHERE topic_id = '$topic_id'";
$consulta_nota_geral_conect = mysqli_query($conn,$consulta_nota_geral) or die (mysqli_error($conn));
if(mysqli_num_rows($consulta_nota_geral_conect) > 0) {
//other code here
}
I assume by incompatibility you mean that mysqli_num_rows() returns 1. It is because AVG() groups the rows into one and then computes the average.
If you want to get the real number of rows, you can use COUNT(*).
So, your query would be:
SELECT COUNT(*) as number_of_rows, avg(comp1) as competencia1 , avg(comp2) as competencia2 , avg(comp3) as competencia3 , avg(comp4) as competencia4 , avg(comp5) as competencia5 FROM votos WHERE topic_id = '$topic_id'
Then, you would use mysqli_fetch_row() or mysqli_fetch_assoc() to get the data.
$consulta_nota_geral = "SELECT COUNT(*) as number_of_rows, avg(comp1) as competencia1 , avg(comp2) as competencia2 , avg(comp3) as competencia3 , avg(comp4) as competencia4 , avg(comp5) as competencia5 FROM votos WHERE topic_id = '$topic_id'";
$consulta_nota_geral_conect = mysqli_query($conn,$consulta_nota_geral) or die (mysqli_error($conn));
$data = mysqli_fetch_assoc($consulta_nota_geral_conect);
if($data["number_of_rows"] > 0) {
//your code
}
The sql returns one row because it's using aggregate functions (avg). If you add a count(*) to the select, it will return that with the sql results.
I am trying to use multiple search options where user can select multiple options to filter records.
When user don't select filter option(s), by default all records should be returned.
Here's my SQL query :
$query =
sprintf("SELECT * FROM users_leave_request
where leave_from >= '$leave_from'
AND leave_to <= '$leave_to'
AND leave_status = '$leave_stat'
AND user_id = '$emp_id'");
$result=$this->db->exec($query);
What I intend to do is that:
Suppose $leave_stat parameter is empty, then records for all leave_stat values should be returned.
Similarly if $emp_id is empty, records for all users should be returned.
It's somewhat like disabling that *extra AND* where condition when parameter is empty.
Can I do this with a single query or do I have to use separate queries for that?
Any help is very much appreciated. Thanks.
You can check the filter condition before the query, like this
$whrcondn="";
$whrcondn.=($leave_from)?" and leave_from > = '$leave_from'":"";
$whrcondn.=($leave_to)?" and leave_to < = '$leave_to'":"";
$whrcondn.=($leave_status)?" and leave_status = '$leave_stat'":"";
$whrcondn.=($emp_id)?" and user_id ='$emp_id'":"";
$query = sprintf("select * from users_leave_request where 1=1 $whrcondn");
look at this simple way
add this condition
if(!empty($leave_stat))
{$x='leave_status';}
else
{$x='leave_status!';}
if(!empty($leave_stat))
{$y='user_id';}
else
{$y='user_id!';}
then change leave_status and user_id by $x and $y like this :
$query = sprintf("SELECT * FROM users_leave_request
where leave_from >= '$leave_from'
AND leave_to <= '$leave_to'
AND '$x' = '$leave_stat'
AND '$y' = '$emp_id'");
$result=$this->db->exec($query);
and good luck
I have an SQL query that fetches posts from a database. Everything works fine, but now I need to order the results by the number of comments each post has. The comments are on a separate table and they have a post_id column that links it to the post. I need to order the posts by the count of the comments table based on a shard ID? I have tried everything but every time I try to add something to my query it stops running completely and leaves my page blank. I need help to know where to put the other JOIN statement. This is my query:
$union = "UNION ALL
(
SELECT DISTINCT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
LEFT JOIN walllikes_track
ON wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id."
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) ";
The comments table is called wallcomments and it has a column called post_id. I know I need to use JOIN and COUNT but I don't know where to put it within my current code.
Try this query, I didn't run but i updated it.
SELECT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by ) " AND wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id.";
A more readable query might look like this...
At least then we'd have a chance.
SELECT DISTINCT p.p_id
, p.is_profile_notes
, p.times_viewed
, p.columnTimesShared
, p.marked
, p.secure_id
, p.media...
FROM wallposts p...
I am using count function to get the number of rows buffered in a resultset.
But it always returns count as one even if resultset is empty.
Please see the code below:
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
print count($resQuery1);
What am I doing wrong and how can I fix this?
As per your comment if you just want to return the count of records you could wrap your query in a SELECT COUNT(*) and change $dbhandle->query to $dbhandle->querySingle. This will work with or without LIMIT.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT COUNT(*) FROM (SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10)";
$resQuery1 = $dbhandle->querySingle($selQuery1);
print count($resQuery1);
Result is an array. find the size of the array.
$dbhandle = new SQLite3("sqlitedb_111.db");
$selQuery1 = "SELECT id,dbname,tabname,fieldname FROM scan_results ORDER BY id ASC LIMIT 0,10";
$resQuery1 = $dbhandle->query($selQuery1);
$noofrows=sizeof($resQuery1);
echo $noofrows;
SQLite is an embedded database, i.e., there is no client/server communication overhead.
Therefore, it can return the results dynamically; there is only a single row buffered at any time.
To get the number of result rows, you either have to step through the results, or execute something like SELECT COUNT(*) FROM (original query).
Call numRows() on the result set.
From http://php.net/manual/en/function.sqlite-num-rows.php
<?php
$db = new SQLiteDatabase('mysqlitedb');
$result = $db->query("SELECT * FROM mytable WHERE name='John Doe'");
$rows = $result->numRows();
echo "Number of rows: $rows";
?>
I want to get all rows count in my sql.
Table's first 2 columns look like that
My function looks like that
$limit=2;
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $total, $datetime, $title, $content);
$stmt->store_result();
$count = $stmt->num_rows;
if ($count > 0) {
while ($stmt->fetch()) {
Inside loop, I'm getting exact value of $total, but MySQL selects only 1 row - row with id number 1. (and $count is 1 too)
Tried this sql
SELECT id,dt,title,content FROM news ORDER BY dt DESC LIMIT 2
All goes well.
Why in first case it selects only 1 row? How can I fix this issue?
for ex my table has 5 rows. I want to get 2 of them with all fields, and get all rows count (5 in this case) by one query.
Remove COUNT(*). You will only ever get 1 row if you leave it in there.
Try adding GROUP BY dt if you want to use COUNT(*) (not sure why you're using it though).
EDIT
Fine, if you insist on doing it in a single call, here:
$sql = "SELECT id,(SELECT COUNT(id) FROM news) as total,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
This is likely cause by the variable $limit being set to 1, or not being set and mysql defaulting to 1. Try changing your first line to
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC";
EDIT
Change to:
$sql = "SELECT SQL_CALC_FOUND_ROWS,id,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
And then use a second query with
SELECT FOUND_ROWS( )
to get the number of rows that match the query
This totally wreaks of a HW problem... why else besides a professor's retarded method to add complexity to a simple problem would you not want to run two queries?
anyways.... here:
SELECT id, (SELECT COUNT(*) FROM news) AS row_count, dt, title, content FROM news ORDER BY dt DESC LIMIT