I have this query. However, it does not work properly. The echo returns always a 1, but there are 3 rows in the db
<?php
include "db_connect.inc.php";
$sql = "SELECT COUNT(id) FROM profiles";
$res = mysqli_query($con, $sql);
$num = mysqli_num_rows($res);
if ($num == 0)
echo "0";
echo $num;
mysqli_close($con);
?>
You're doing an aggregate query, which means you'll ALWAYS get one row of results - one row containing the count() value you requested. Even if that count() is 0, you'll STILL get one row of results.
If you want to check the value of the count, you have to fetch that row and check the field's value, e.g.
$sql = "SELECT COUNT(id) AS cnt FROM profiles";
$result = mysqli_query($con, $sql) or die(mysqli_error($con));
$row = mysqli_fetch_assoc($result);
if ($row['cnt'] == 0) { die("No profiles"); }
Your query returns 1 row with value 3
To see what you do expect you need something like:
<?php
include "db_connect.inc.php";
$sql = "SELECT COUNT(id) myCount FROM profiles";
$res = mysqli_query($con, $sql);
if ($row = mysqli_fetch_array($res, MYSQLI_ASSOC) ) {
echo $row['myCount'];
} else {
echo "0";
}
mysqli_close($con);
?>
Related
I have been trying to compare value in a table with another value in another table but only the else part is executing.
<?php
$sql = "SELECT * FROM user WHERE user_id=$row[user_id]";
$result = $conn -> query ($sql);
if ($result -> num_rows > 0) {
while ($row = $result ->fetch_assoc()) {
$sql1 = "SELECT * FROM jobpost WHERE jobpost_id=$_GET[id] ";
$result1 = $conn -> query ($sql1);
$row_count = mysqli_num_rows($result);
$row1_count = mysqli_num_rows($result1);
$remaining_rows = min($row_count, $row1_count);
$row = mysqli_fetch_assoc($result);
$row1 = mysqli_fetch_assoc($result1);
if($row["experience"] > $row1["experience"])
{
//some code to display something
echo "1";
}
else
{
echo "2";
}
} }
?>
Welcome to SO, it is hard to read your source code. You can use a simple query like this:
SELECT IF(u.experience > j.experience,1,0) FROM
(
(SELECT experience FROM user WHERE user_id = 1) u
JOIN
(SELECT experience FROM jobpost WHERE jobpost_id = 8) j
)
Try this query here: http://sqlfiddle.com/#!9/1742c0
Please check our datasource. Maybe the else case is correct.
I have a page that is taking a kind of long time to load, and I'm almost sure that this is caused by too many sql requests (AKA caused by my bad SQL skills). Is there anyway to join these 3 queries into one?
What I want to do with this query is to try to select a specific id from cardapios and, if there is anything there (if $num_rows > 0) the only thing I want to do is select that id. If there is nothing there, then I want to insert something and then select the id of that.
$query = "SELECT id FROM cardapios WHERE nome='$nome'";
$sql = mysqli_query($con,$query);
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0){
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
$num_rows = 0;
}}else{
$query = "INSERT INTO cardapios (nome, kcal, semana)
VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
$sql = mysqli_query($con,$query);
$query = "SELECT id FROM cardapios WHERE nome='$nome' ";
$sql = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
}
}
I am trying to put all of this into one query but getting nowhere. Is there anyway to use just one query for doing all of this?
Thanks in advance!
You can replace the last query by getting the mysqli_insert_id($con); as you already have the insert id available after the insert
$query = "SELECT id FROM cardapios WHERE nome='$nome'";
$sql = mysqli_query($con,$query);
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0){
while ($row = mysqli_fetch_array($sql)){
$_SESSION['id_cardapio'] = $row['id'];
$num_rows = 0;
}
}else{
$query = "INSERT INTO cardapios (nome, kcal, semana)
VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
$sql = mysqli_query($con,$query);
if ( $sql !== false) { // did insert work
$_SESSION['id_cardapio'] = mysqli_insert_id($con);
} else {
// insert did nto work??
}
}
Not a duplicate of Select specific value from a fetched array
I have a MySql database as:
Here's my query:
$sql = "SELECT * FROM data ORDER BY Score DESC";
I want it to be a leaderboard which people can update their scores so I can't use
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
I want to get Username of the second row in my query.So I wrote:
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
}
echo "Result = '".$row[1]['Username']."''";
}
?>
But it returns Result = '' like there's nothing in the array.
But if I write
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Name = '".$row['Username']."''";
}
}
It will return : Parham, Mojtaba, Gomnam, Masoud,
So what am I doing wrong in the first snippet?
You can not access $row outside of while loop.
So store result in one new array, and then you can access that new array outside the while loop:
$newResult = array();
if($result->num_rows>0){
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$newResult[] = $row;
}
}
echo "Result = '".$newResult[1]['Username']."''"; // thus you can access second name from array
Because you write where condition after ORDER by at
$sql = "SELECT * FROM data ORDER BY Score DESC WHERE ID = 1";
The sequence of query is
SELECT * FROM data // select first
WHERE ID = 1
ORDER BY Score DESC// Order by at last
Check http://dev.mysql.com/doc/refman/5.7/en/select.html
And for second case you need to fetch Username inside while loop and use $row['Username'] instead $row[1]['Username']
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "Result = '".$row['Username']."''";// write inside while loop
}
You can assign row value to any array and use that array.
<?php
include "l_connection.php";
$sql = "SELECT * FROM data ORDER BY Score";
$result = mysqli_query($conn, $sql);
if($result->num_rows>0){
$rows = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$rows[] = $row;
}
echo "Result = '".$rows[1]['Username']."'";
}
?>
Or if you want only second highest score from column you can user limit as
$sql = "SELECT * FROM data ORDER BY Score limit 1,1";
Based on my codes, i need to restrict the insertion of the data by 3, i mean is like after the insertion of 3 data row, it will be restricted from inserting in data. Is that possible? For more information, is like the borrow inserting 3 times, then it cannot be inserted anymore. Is there anyway to do so? I am still learning php by the way, thank you.
if(isset($_POST['selector']))
$id=$_POST['selector'];
else
$id = '';
$member_id = $_POST['member_id'];
$due_date = $_POST['due_date'];
$isbn = $_POST['due_date'];
if ($id == '' ){
//header("location: borrow.php");
if(isset($_POST['isbn'])){
$isbn = $_POST['isbn'];
$query = mysql_query("select book_id from book WHERE isbn = '$isbn'")or die(mysql_error());
$count = mysql_num_rows($query);
if($count > 0){
$row = mysql_fetch_array($query);
$bookid = $row['book_id'];
$date = date('Y-m-d');
}
mysql_query("insert into borrow (member_id,book_id,date_borrow,due_date) values ('$member_id','$bookid','$date','$due_date')")or die(mysql_error());
}
else{
header("location: borrow.php");
}
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
mysql_query("insert borrowdetails (book_id,borrow_id,borrow_status)
values('$id[$i]','$borrow_id','pending')")or die(mysql_error());
}
header("location: borrow.php");
}
You just have to count number of user row before to make a new insert :
$query = mysql_query("SELECT COUNT(*) AS count FROM borrow WHERE member_id = '".$member_id."'");
$row = mysql_fetch_assoc($query);
if ( $row['count'] >= 3 )
echo('Max insert');
Also, check this : Why shouldn't I use mysql_* functions in PHP?
I'm not sure I understand you correctly.
You can restrict the number of rows returned by SELECT query using the LIMIT clause.
Make sure you either put an ORDER BY clause in there or determine that you don't care 'which' 3 rows will get inserted.
See here:
http://dev.mysql.com/doc/refman/5.0/en/select.html
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
If 'table' has no rows. whats the easiest way to check for this.?
Jeremy Ruten's answer above is good and executes quickly; on the other hand, it only gives you the number of rows and nothing else (if you want the result data, you have to query the database again). What I use:
// only ask for the columns that interest you (SELECT * can slow down the query)
$query = "SELECT some_column, some_other_column, yet_another_column FROM `table`";
$results = mysql_query($query, $connection);
$numResults = mysql_num_rows($results);
if ($numResults > 0) {
// there are some results, retrieve them normally (e.g. with mysql_fetch_assoc())
} else {
// no data from query, react accordingly
}
You could use mysql_num_rows($results) to check if 0 rows were returned, or use this faster alternative:
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
Alternatively you can simply check if the result of mysql_fetch_assoc is false.
$query = "SELECT * FROM `table`";
$results = mysql_query($query, $connection);
$Row = mysql_fetch_assoc($results);
if ($Row == false)
{
$Msg = 'Table is empty';
}
One thing i noticed that was missed was the fact that the query might not succeed, so you do need to check if the $results variable is set. I'll use the answer given by yjerem as an example.
$query = "SELECT COUNT(*) AS total FROM table";
$results = mysql_query($query, $connection);
if ($results) { // or use isset($results)
$values = mysql_fetch_assoc($results);
$num_rows = $values['total'];
}
If you loop through the results, you can have a counter and check that.
$x = 1;
$query = mysql_query("SELECT * FROM table");
while($row = mysql_fetch_assoc($query))
{
$x++;
}
if($x == 1)
{
//No rows
}