My problem is this: I found a easy and fast way to get random row in my table. First, i am using query, which counts my ids from my table. Second, i generate random number from 1 to result of count query. Third, i am selecting row from my table where id is equal to my random generated number. Everything works fine, but the problem is that sometimes query displays me blank page with no information given, with no error given.
here is my code:
$viso = $stmt = $db->query("select count(id) from intropage")->fetchColumn();
$min=1;
$max= $viso;
$lopas=rand($min,$max);
$stmt = $db->query('SELECT * FROM intropage WHERE id='.$lopas.'');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
... }
How can i fix this "blank page" issue?
Thanks to all of you for any answers!
It's not fast method, because you are using double request to db AND you are exposed to SQL injection. Try:
$query = $db->prepare('SELECT * FROM intropage ORDER BY RAND() LIMI 1');
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
/* */
}
I think it will fix your blank page error too. If not, turn on error reporting and tell us what error you get.
Is error_reporting activated ?
Your query is wrong so an error is throw and you probably cannot see it
$db->query("SELECT * FROM intropage WHERE id='".$lopas."'");
Also, a better way to have random row, is to use RAND()
$db->query("SELECT * FROM intropage ORDER BY RAND() LIMIT 1");
Related
I've been using this command to retrieve the number of the fields which have same email address:
$query = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `email`='$email'") or die($db-error);
There are 3 records in users table with the same email address. The problem is when I put * instead of COUNT(user_id) it returns correctly: $query->num_rows gives 3 but when I use COUNT(user_id) then $query->num_rows returns 1 all the time. how can I correct this or where is my problem?
When you use $query->num_rows with that query it will return 1 row only, because there is only one count to return.
The actual number of rows will be contained in that query. If you want the result as an object, or associative array give the count a name:
$query = $db->query("SELECT COUNT(`user_id`) AS total FROM `users` WHERE `email`='$email'") or die($db-error);
And in the returned query total should be 3, while $query->num_rows will still be 1. If you just want the value a quick way would be using $total = $query->fetchColumn();.
As others have said though, be careful with NULL user ids, because COUNT() will ignore them.
Emails have to be uinque in users table. Thus, you need no count at all.
You ought to use prepared statements.
You shouldn't post a code that will never run.
Here goes the only correct way to run such a query:
$sql = "SELECT * FROM `users` WHERE `email`=?";
$stm = $db->prepare($sql);
$stm->execute([$email]);
$user = $stm-fetch();
(the code was written due to erroneous tagging. For mysqli you will need another code, but guidelines remains the same.)
Something like this
$sql = "SELECT * FROM `users` WHERE `email`=?";
$stm = $db->prepare($sql);
$stm->bind_param('s',$email);
$stm->execute();
$res = $stm->get_result()
$user = $res->fetch_assoc();
in $user variable you will have either userdata you will need in the following code or false which means no user found. Thus $user can be used in if() statement all right without the need of any counts.
In case when you really need to count the rows, then you use this count() approach you tried. You can use a function from this answer for this:
$count = getVar("SELECT COUNT(1) FROM users WHERE salary > ?", $salary);
That's the correct behaviour: If you use the COUNT function, the result of your select query will be just one row with one column containing the number of data sets.
So, you can retrieve the number of users with the given E-mail address like this:
$query = $db->query("SELECT COUNT(`user_id`) FROM `users` WHERE `email`='$email'") or die($db-error);
$row = $query->fetch_row();
$count = $row[0];
Note that this is faster than querying all data using SELECT * and checking $query->num_rows because it does not need to actually fetch the data.
I have made " news & updates " simple script
my query is:
$query = mysql_query("SELECT * FROM a_commants WHERE postid='$postid' ORDER BY id DESC LIMIT 0,10");
it shows last comment
i want to make it show all comments or at least 10 comments
if i change it to:
$query = mysql_query("SELECT * FROM a_commants WHERE
postid='$postid'");
it shows first comment only
idk whats wrong :(
I think that the problem is in your php code, not MySQL.
The query seems fine, as long as you have more than one comment, but it seems that you are not iterating through results, just printing the first row you get from db.
This should show last 10 comments:
$res = mysql_query("SELECT * FROM a_commants WHERE postid='$postid' ORDER BY id DESC LIMIT 0,10");
while($row = mysql_fetch_array($res)){ // iterate through results
print_r($row); // print the row
}
And you should definitely switch to mysqli or PDO, and sanitize your inputs.
The mysql_* functions are deprecated and going to be removed from PHP.
This is my script atm, and it doesn't load more images. I really don't know what i'm doing wrong? I've tried first converting my mysql to pdo, it loads the first set of images, but when i visit my website, it already says, "No more content" at top, and can't scroll to infinite.
See the new code!
EDIT
Oke so I did it step by step and this doesn't work well. I tried it like this:
$result2 = $pdo->prepare("SELECT * FROM scroll_images ORDER BY id ASC LIMIT ?");
$result2->execute(array($set_limit));
Doesn't work, only when I use it like this:
$result2 = $pdo->query("SELECT * FROM scroll_images ORDER BY id ASC LIMIT $set_limit");
Why is that?
NEW EDIT!
So the data thing is working, now the index. The first statement works, because it load's the first images. But now the rest of the query for getting all the rows in one query and get it with FOUND_ROWS()
Code:
$result = $pdo->query("SELECT SQL_CALC_FOUND_ROWS * FROM scroll_images ORDER BY id ASC limit 12"); // This works, but don't know about the sql_calc_found rows part.
$resultALL = $pdo->query("SELECT FOUND_ROWS() AS rowcount");
$resultALL->fetch(PDO::FETCH_OBJ);
$actual_row_count = $resultALL->rowcount; // doesn't return anything.
I'm an SQL noob and learning how to use PDO. I'm doing a course which introduces basic user login functions. In an example of a login page, they check the username/password against a MySQL database. I edited their code slightly to be able to simultaneously check whether the user/pass combo exists and also grab the user's first name:
$sql = sprintf("SELECT firstname FROM users WHERE username='%s' AND password='%s'",
mysql_real_escape_string($_POST["username"]),
mysql_real_escape_string($_POST["password"]));
// execute query
$result = mysql_query($sql);
if (mysql_num_rows($result) == 1) {
$_SESSION["authenticated"] = true;
// get contents of "firstname" field from row 0 (our only row)
$firstname = mysql_result($result,0,"firstname");
if ($firstname != '')
$_SESSION["user"] = $firstname;
}
What I want to do is use SQLite instead and do the same thing. Searching around has only resulted in people saying you should use a SELECT COUNT(*) statement, but I don't want to have to use an extra query if it's possible. Since I'm SELECTing the firstname field, I should only get 1 row returned if the user exists and 0 if they don't. I want to be able to use that number to check if the login is correct.
So far I've got this:
$dsn = 'sqlite:../database/cs75.db';
$dbh = new PDO($dsn);
$sql = sprintf("SELECT firstname FROM users WHERE username='%s' AND password='%s'",
$_POST["username"],
$_POST["password"]);
// query the database and save the result in $result
$result = $dbh->query($sql);
// count number of rows
$rows = sqlite_num_rows($result);
if ($rows == 1) { ...
But this is returning Warning: sqlite_num_rows() expects parameter 1 to be resource, object given.
Is there a way I can do this efficiently like in MySQL, or do I have to use a second query?
EDIT:
I found this, not sure if it's the best way but it seems to work: How to get the number of rows grouped by column?
This code let me do it without the second query:
// query the database and save the result in $result
$result = $dbh->query($sql);
// count number of rows
$rows = $result->fetch(PDO::FETCH_NUM);
echo 'Found: ' . $rows[0];
$rows is an array so I can just count that to check if it's > 0.
Thanks to everyone who commented. I didn't know until now that there were 2 different approaches (procedural & object oriented) so that helped a lot.
Normally, you can use PDOStatement::rowCount(), however, SQLite v3 does not appear to provide rowcounts for queries.
You would need to seperately query the count(*), or create your own counting-query-function.
The documentation comments have an example of this
A bit late, but i tried this with SQLite3 successful:
$result = $db->query('SELECT * FROM table_xy');
$rows = $result->fetchAll();
echo count($rows);
i got a fairly simple layout going and for the life of me i cant figure out why this returns nothing:
<?php
// Gets A List Of Comic Arcs
$result = mysql_query("SELECT * FROM ".$db_tbl_comics." GROUP BY ".$db_fld_comics_arc." ORDER BY ".$db_fld_comics_date." DESC LIMIT 20");
while ($comic = mysql_fetch_array($result)) {
// Now Go Back And Count Issues For Each Comic Arc Above
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."=".$comic[$db_fld_comics_arc]);
$total_issues = mysql_num_rows($result22);
echo $total_issues;
}
?>
No other query is refered to as $result22.
$comic[] has already been defined in the previous query.
echo mysql_error($result22); returns no errors.
Let me know if you need any other info.
I am assuming that the column $db_fld_comics_arc is a string.
Change:
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."=".$comic[$db_fld_comics_arc]);
To:
$result22 = mysql_query("SELECT * FROM ".$db_tbl_comics." WHERE ".$db_fld_comics_arc."='".$comic[$db_fld_comics_arc]."'");
Am I wrong? If so, let me know the table structure, and what your error reporting is set to.
Also, could you let us know the purpose of your SQL? It may also be possible to put the data together in one query, instead of looping sql queries through, and using data from a first query.
Maybe it is because $db_fld_comics_arc is in $comic[$db_fld_comics_arc]
if both are the same then you should try replacing $db_fld_camics_arc with $comic[$db_fld_comics_arc].