Echoing out a date from a query - php

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

Related

How to select the maximum value of a column in MySQL

I want to select the maximum value of a column of my table. I'm using PHP and MySQL. This is what I have so far:
$max = "SELECT MAX(Id) FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
echo= $max1;
My debugger is just saying that it is a query returning a 0 boolean value (false). I cannot find a specific answer anywhere on the internet.
You need to fetch the data from the mysqli_result object that was returned to you when you executed your query using mysqli_query.
$max = "SELECT MAX(Id) as id FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1); // this was missing
$id=$row['id'];
echo $id;
Note: I removed the loop because with MAX query without any grouping you will get only 1 row returned. If you had multiple rows in result set you would need to loop through all of them
two ways
first is as people described
$max = "SELECT MAX(Id) as max_id FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1);
$max_id=$row['max_id'];
echo $max_id;
second is ordering and limiting
$max_id = 0;
$max = "SELECT id FROM trialtabel2 order by id desc limit 0,1";
$max1 = mysqli_query($dblink, $max);
while($row = mysqli_fetch_assoc($max1)){
$max_id=$row['id'];
}
echo $max_id;
In Your code you missing the fetch statement. you need to fetch from the resultset. see above what you are missing.
Try using this..,
$max = "SELECT MAX(Id) as maxId FROM trialtabel2";
$max1 = mysqli_query($dblink, $max);
$row = mysqli_fetch_assoc($max1);
echo $row['maxId'];
Hope this helps..
$max = "SELECT Id FROM trialtabel2 order by id desc limit 1";
$max1 = mysqli_query($dblink, $max);
$result = mysqli_fetch_assoc($max1);
pre($result);

PHP integer variable in mySQL query

I'm trying to input a PHP variable (in this case $beg) into a mySQL query but it returns an empty array result. The type of the field in the database is an integer. When I type in an actual value instead of the variable I get the correct result. What's wrong?
$beg = time()-5000;
settype($beg, "integer");
$result = mysql_query('SELECT * FROM records WHERE time>=$beg ORDER BY time ASC');
$statusdata = array();
while ($row = mysql_fetch_array($result)) {
array_push($statusdata, $row["status"]);
}
Make sure you use double quotes when using $variables inside the string.
$result = mysql_query("SELECT * FROM records WHERE time>= $beg ORDER BY time ASC");
You should use prepared statements instead of mysql_query.
$beg = time()-5000;
settype($beg, "integer");
$db = new mysqli("host","user","pw","database");
$stmt = $db->prepare("SELECT status FROM records WHERE time>=? ORDER BY time ASC");
$stmt->bind_param('i', $beg);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($status);
$statusdata = array();
while($stmt->fetch())
{
array_push($statusdata, $status);
}
$stmt->close();
Change the line
$result = mysql_query("SELECT * FROM records WHERE time>=$beg ORDER BY time ASC");
You must use double quote strings to put variables.
Change your query
$result = mysql_query(" SELECT * FROM records WHERE time >= $beg ORDER BY time ASC ");
You cannot use variable inside single quotes.
try this method, I use a lot:
$beg = time() - 5000;
$query = sprintf("SELECT * FROM %s WHERE time >= '%o' ORDER BY %s ASC", "records", $beg, "time");
$result = mysql_query($query);
remeber, time() result is Integer, you don't need set him in to an Integer

Is this query safe to use? Prepared statement?

Is this query safe to use? I'm not sure how I'd convert it to a prepared statement as it's not using any values from the user:
$result = mysqli_query($cxn, "SELECT * FROM table WHERE datetime > DATE_SUB(NOW(), INTERVAL 15 DAY) ORDER BY RAND() LIMIT 1");
while ($row = mysqli_fetch_array($result)) {
$title = $row['title'];
echo $title;
}
Is this safe to use? How can I improve it?
Thanks.
Yes, it's safe. There is no user input used there at all; nothing that has the potential to mess up the query syntax or manipulate the outcome in any way.
As for improvements, there is no need to return every field in the table if you are only using the title field. In general, you should avoid the wild-card (*) for SELECT queries, except for testing purposes.
Also, the DATE_SUB(NOW(), INTERVAL 15 DAY) can be reduced to just NOW() - INTERVAL 15 DAY. Shorter and sweeter; no unnecessary function calls.
The biggest improvement you can make is to change
SELECT * FROM table WHERE datetime > DATE_SUB(NOW(), INTERVAL 15 DAY) ORDER BY RAND() LIMIT 1
to
SELECT title FROM table WHERE datetime > DATE_SUB(NOW(), INTERVAL 15 DAY) ORDER BY RAND() LIMIT 1
because you are only using the title column in your code.
Yes it is safe. It's best to use prepared statement if you decided to pass parameter to your sql.
here is example for you with parameter :
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
here is example/answer for your sql:
$stmt = $dbConnection->prepare('SELECT * FROM table WHERE datetime > DATE_SUB(NOW(), INTERVAL 15 DAY) ORDER BY RAND() LIMIT 1');
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}

QL_CALC_FOUND_ROWS pdo?

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!

php MySQL query not returning anything

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];
}

Categories