i'm new in PDO and now i'm facing this
Uncaught Error: Unsupported operand types
in mysql_ (old way) it work just fine to set to divide limit with rows, but it won't work with PDO,
this is the old way
limit is 4 start from 0, the database is more than 100 to count, the logic just fine
$query=mysql_query("SELECT * FROM `articles` LIMIT $start, $limit");
$rows=mysql_num_rows(mysql_query("SELECT * FROM `articles`"));
$total=ceil($rows/$limit);
and with the PDO (new way they said)
$query=$db -> query("SELECT * FROM `articles` LIMIT $start, $limit");
$rows=$query->fetch(PDO::FETCH_ASSOC);
$total=ceil($rows/$limit);
and i get the error msg, any clues?
In your mysql_-example you are explicitly fetching the rowcount of a query.
In your PDO implementation you are only fetching one result from the resultset your query returned. You could do something like this:
$query = $db->query("SELECT * FROM `articles` LIMIT $start, $limit");
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
$total = ceil(count($rows)/$limit);
edit: If it is only about counting the rows you should to so in the db.
$query = $db->query("SELECT count(*) AS rowcount FROM `articles` LIMIT $start, $limit");
$rows = $query->fetch(PDO::FETCH_ASSOC);
$total = ceil($rows['rowcount']/$limit);
Related
$sql = "SELECT `url`,`title`,`vid` FROM `video` ORDER BY `time` DESC limit 15";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
This SQL can select the top new 15 rows data.
I want display the top new 100, but just show 15
How to select faster?
$sql = "SELECT `url`,`title`,`vid` FROM `video` ORDER BY `time` DESC limit 100";
i assume that $row[0] => gives first record.
--
function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
$numbers = range($min, $max);
shuffle($numbers);
return array_slice($numbers, 0, $quantity);
}
--
foreach (UniqueRandomNumbersWithinRange(0,100,15) as $row_number)
{
$content=$row[$row_number];
echo $content['title'];
}
Well you could try fixing it like:
<?php
//get the max count for the table;
$max="SELECT id FROM video order by time desc LIMIT 1";
$start="SELECT id FROM video order by time desc LIMIT 100, 1";
$page_size=15;
$rand_no=rand(start,$max - page_size);
$result_set="SELECT * FROM video order by time LIMIT $rand_no,page_size";
NB: it's an abstract code explains the logic.
I'm trying to convert a script from basic sql to pdo. I'm not so good at it, but i have come this far that my pdo returns all the rows in the database (limit 12) i can make 2 statements one without the limit and one with the limit. but in the sql that is originally there, it uses QL_CALC_FOUND_ROWS what this does I think, is that i returns the total rows, and the limit rows, so that the query is faster.
How can i do it with PDO ?
CODE:
<?
// NORMAL SQL
$result = mysql_query('SELECT SQL_CALC_FOUND_ROWS * FROM photos ORDER BY id ASC limit 12');
$row_object = mysql_query('SELECT Found_Rows() AS rowcount');
$row_object = mysql_fetch_object($row_object);
$actual_row_count = $row_object->rowcount;
// PDO
$result = $pdo->prepare('SELECT * FROM photos ORDER BY id ASC limit 12');
$result->execute();
$TOTALrows = $result->rowCount();
?>
EDIT:
Tried some things but this won't work:
$result = $pdo->prepare('SELECT SQL_CALC_FOUND_ROWS * FROM photos ORDER BY id ASC limit 12');
$result->execute();
$resultALL = $pdo->prepare('SELECT Found_Rows() AS rowcount');
$resultALL->execute();
$resultALL->fetch(PDO::FETCH_OBJ);
$actual_row_count = $resultALL->rowcount;
EDIT2: Still no success..
$result = $pdo->query('SELECT SQL_CALC_FOUND_ROWS * FROM photos ORDER BY id ASC limit 12');
$resultALL = $pdo->query('SELECT Found_Rows() AS rowcount');
$resultALL->fetch(PDO::FETCH_OBJ);
$actual_row_count = $resultALL->rowcount;
print_r($actual_row_count);
echo $actual_row_count;
Doesn't echo anything.
Credits also go to Explosion Pills here...
When you're not feeding your query with external input, you don't really have to prepare your statement:
$result = $pdo->query("SELECT SQL_CALC_FOUND_ROWS * FROM photos ORDER BY id ASC LIMIT 12");
This should work!
I'm not sure exactly how to explain what the query does, however the problem isn't entirely with how it's set up, because it does work, in another instance, when I use it as an array, however it's not working when I use it with mysql_fetch_assoc(), so here is what my original query is(not the one im having trouble with):
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC
what this does is selects the last 3 comments on a post, then orders them in another way (so they show up in the correct order, old to new) Now this is the query for echoing out the array of comments directly.
But now what I want to do, is to just get the first id out of the 3 comments.
here's what I have tried to do (and by the way, this query DOES work, when i replace my previous query to echo out the results in an array, but i need to get just the id for use, i don't want an array):
$previousIDq = mysql_fetch_assoc(mysql_query("
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1"));
$previousID = $previousIDq['id']; //this doesn't return the id as I want it to.
Your problem may be that there are no matching rows.
Also, I think you could also improve your query to this:
SELECT * FROM comments WHERE postID='$id' AND state='0' ORDER BY id DESC LIMIT 2,1
But as others say, use PDO or MySQLi, and with prepared statements. And don't SELECT * ever.
try a var_dump($previousID) to see what you get
It is probably giving you back an object, and you need to get your id from that object
You script is too condensened for error handling, let alone debugging
$mysql = mysql_connect(...
$query = "
SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1
";
$result = mysql_query($query, $mysql);
if ( !$result ) { // query failed
die('<pre>'.htmlspecialchars(mysql_error($mysql)).'</pre><pre>'.htmlspecialchars($query).'</pre>');
}
$previousIDq = mysql_fetch_assoc($result);
if ( !$previousIDq ) {
die('empty result set');
}
else {
$previousID = $previousIDq['id'];
}
You need to separate your code to be able to debug
$query = "SELECT * FROM
(SELECT * FROM comments
WHERE postID='$id' AND state='0'
ORDER BY id DESC LIMIT 3
) t ORDER BY id ASC LIMIT 1";
$result = mysql_query($query);
echo mysql_error(); //what eror comes out here
while($previousIDq = mysql_fetch_assoc($result))
{
print ($previousIDq['id']);
}
NOTE: mysql_* is depreciated, upgrade to mysqli or PDO
Please stop using mysql_ functions to write new code, it is being deprecated. Use mysqli_ or PDO functions (mysqli below).
Bind your parameters to prevent SQL injection
Always use a column list (don't use SELECT *)
If you're returning > 1 row, use a while loop
mysqli_ solution
$link = mysqli_connect("localhost", "user_name", "password", "stock");
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
$stmt = mysqli_prepare($link, "SELECT t.id FROM
(SELECT id FROM comments
WHERE postID = ? AND state = 0
ORDER BY id DESC
LIMIT 3) t
ORDER BY id ASC");
mysqli_bind_param($stmt, 's', $id) or die(mysqli_error($dbh));
$result = mysqli_stmt_execute($stmt) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($result)) {
echo $row[id];
}
mysqli_close($link);
mysql_ solution
$stmt = "SELECT t.id FROM
(SELECT id FROM comments
WHERE postID = $id AND state = 0
ORDER BY id DESC
LIMIT 3) t
ORDER BY id ASC";
$result = mysql_query($stmt) or die(mysql_error());
$row = mysql_fetch_assoc($result);
while($row = mysql_fetch_assoc($result)) {
echo $row[id];
}
I would like $minutes below to be the oldest datecommented from the query (expressed in minutes). When I echo $minutes out, I get a blank result. What am I doing wrong?
$queryuidcount = "SELECT loginid, datecommented
FROM comment
WHERE (HOUR(NOW()) - HOUR(datecommented)) <= 1
AND loginid = '$uid'
ORDER BY datecommented ASC
LIMIT 1'";
$row2 = mysql_fetch_array($queryuidcount);
$minutes = $row2["datecommented"];
You need to execute mysql_query() on your query before you call mysql_fetch_array() on the result. Try this:
$result = mysql_query('SELECT loginid, datecommented FROM comment WHERE (HOUR(NOW()) - HOUR(datecommented)) <= 1 AND loginid = '$uid' ORDER BY datecommented ASC LIMIT 1');
$row = mysql_fetch_array($result);
$minutes = $row['datecommented'];
If your query returns multiple rows, you'll need to iterate through them with a while loop:
while($row = mysql_fetch_array($result)) {
//Fetch values from $row
}
Also, consider using PDO instead of the mysql function family.
I think you are doing it in the wrong way. Here you can find some examples.
mysql_fetch_array is not for DB connection or sql query.
http://php.net/manual/en/function.mysql-fetch-array.php
I am working on PHP. I was working with MySQL before. Here is the code I used -
$offset_result = mysqli_query($con, " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM students ");
$offset_row = mysqli_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysqli_query($con, " SELECT name FROM students LIMIT $offset, 1 " );
$row = mysqli_fetch_row($result);
mysqli_free_result($result);
What will be the corresponding set of statements for SQLite?
Those SQL queries should work in SQLite if you just change RAND to RANDOM and FLOOR(x) to CAST(x AS INTEGER).
A slightly simpler way to do it is to order by a random number:
SELECT name
FROM students
ORDER BY RANDOM()
LIMIT 1
The way you are doing it is more efficient if the table is very large.