PHP integer variable in mySQL query - php

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

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);

count the number of rows in a query

i have this function separated in my working page.
public function countRow(){
$id = $_SESSION['id'];
$num = 1;
$query = "SELECT count(*) from `auditsummary` where bizID=? AND statusID=?";
$sql = $this->db->prepare($query);
$sql->bindParam(1,$id);
$sql->bindParam(2,$num);
$sql->execute();
}
what i'm really trying to do in this function is to count the number of rows that are results of the query but i don't know how to do it and also how to return the value.
As you use a PDOStatement for your query, after the execute, you can use
$count = $sql->rowCount();
More information:
http://php.net/manual/en/pdostatement.rowcount.php
And to return the result, you can just do:
return $count;
Information for this:
http://php.net/manual/en/function.return.php
Use
$query = "SELECT count(*) AS getCount from `auditsummary` where bizID=? AND statusID=?";
And get the values as you normally does
$count = $row["getCount"];
Here's how I do it:
$count = "SELECT * FROM yourtable WHERE x='x' and y='y'";
$result = $dbconn->prepare($count);
$result->execute();
$t_count = $result->rowCount();
echo $t_count;

PDO count records in db with in the current date

I want to count the newly register members but I'm having trouble
$time = new DateTime();
$currentdate = $time->format('Y-m-d');
$cmd=$con->query("select count(*) from user where date(datereg) = ?");
$cmd->execute($currentdate);
$rowcount = $cmd->fetchColumn();
echo $rowcount;
Thank you in advance.
Putting a placeholder inside your query doesn't make sense since you're not preparing it.
$cmd=$con->query("select count(*) from user where date(datereg) = ?");
// ^ query not prepare
$cmd->execute($currentdate); // execute? $cmd is not prepared
Just create a normal query inside it:
$sql = 'SELECT COUNT(*) AS `count` FROM user WHERE DATE(datereg) = CURDATE()';
$result = $con->query($sql);
$count = $result->fetchColumn();

dynamically encode data in json with limit using php for mobile app like android , ios

I have record of 1000 and more records. I have to provide only 50 records per request like
0-50, 50-100, 100-150 like this. I'm using the following code:
public function get_database($data)
<?php
{
$start = $data['start'];
$limit = $data['limit'];
$alumni_details = array();
$query1 = "select * from alumni where
status='Active',limit '".$start."','".$limit."' ";
$query_run = mysql_query($query1);
while($row = mysql_fetch_assoc($query_run))
{
$row['date_of_birth'] = date('d M, Y', strtotime($row['date_of_birth']));
$alumni_detail['alumni_details'] = $row;
$alumni_details[] = $alumni_detail;
}
echo json_encode($alumni_details);
}
But I need to take only user_id based on that I need to encode data in json dynamically with limit.
Your code as below:
$start = $data['start'];
$query = SELECT * FROM `alumni` WHERE `status` = 'Active' ORDER BY `alumni_id` LIMIT $start,5"
It should be dynamic 5 would not be taken as constant. take it in some variable,
and yes it should be fixed, but as per requirement in future it can be change so take it in variable.
$start=$data['start'];
$query=select * from alumni where status='Active' order by alumni_id Limit $start,5"
where 5 is the limit set it according to requirement
$start=$data['start'];
$query=select * from alumni where status='Active' order by alumni_id Limit $start,5"
You have syntax error in your query string.
Use concatenation for example:
$query1 = "select * from alumni where status='Active' limit ".$start.",".$limit;
Or just put variables into double quoted string:
$query1 = "select * from alumni where status='Active' limit $start, $limit";
There is a typo also: you should use $start variable in the query, not $star

How can I add array values to a MySQL query?

I'm using the following code to sort MySQL queries into time/date:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row = mysql_fetch_array($result))
{
print($row['user']);
}
instead of having the PHP run through and show all the values in the table can I have it show the values from an array?
So, you want to find specific users in the SQL query to return? Build your query programmatically:
$users = array('User1','John','Pete Allport','etc');
$sql = "SELECT * FROM `users_newest_post` WHERE ";
$i = 1;
foreach($users as $user)
{
$sql .= "`username` = '$user'";
if($i != count($users))
{
$sql .= " OR ";
}
$i++;
}
$sql .= " ORDER BY `users_date_post` DESC";
$result = mysql_query($sql);
Which would get you a query like:
SELECT * FROM `users_newest_post`
WHERE `username` = 'User1'
OR `username` = 'John'
OR `username` = 'Pete Allport'
OR `username` = 'etc'
ORDER BY `users_date_post`
DESC
So, you want to find all posts for a certain date or between two dates, kinda hard to do it without knowing the table structure, but you'd do it with something like this:
//Here's how to find all posts for a single date for all users
$date = date('Y-m-d',$timestamp);
//You'd pull the timestamp/date in from a form on another page or where ever
//Like a calendar with links on the days which have posts and pass the day
//selected through $_GET like page.php?date=1302115769
//timestamps are in UNIX timestamp format, such as you'd get from time() or strtotime()
//Note that, without a timestamp parameter passed to date() it uses the current time() instead
$sql = "SELECT * FROM `posts` WHERE `users_date_post` = '$date'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
echo $row['post_name'] . $row['users_date_post']; //output something from the posts
}
//Here's how to find all posts for a range of dates
$startdate = date('Y-m-d',$starttimestamp);
$enddate = date('Y-m-d',$endtimestamp);
//Yet again, date ranges need to be pulled in from somewhere, like $_GET or a POSTed form.
//Can also just pull in a formatted date rather than a timestamp and use it straight up instead, rather than going through date()
$sql = "SELECT * FROM `posts` WHERE `users_date_post` BETWEEN '$startdate' AND '$enddate'";
//could also do:
//"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$endate'"
$results = mysql_query($sql);
while($row = mysql_fetch_assoc($results))
{
//output data
}
To find posts for a specific user you would modify the statement to be something like:
$userid = 5; //Pulled in from form or $_GET or whatever
"SELECT * FROM `posts` WHERE `users_date_post` > '$startdate' AND `users_date_post` < '$enddate' AND `userid` = $userid"
To dump the result into an array do the following:
mysql_select_db("user_live_now", $con);
$result = mysql_query("SELECT * FROM users_newest_post ORDER BY users_date_post DESC");
while($row=mysql_fetch_assoc($result))
{
$newarray[]=$row
}
What you probably want to do is this:
$users = array("Pete", "Jon", "Steffi");
$users = array_map("mysql_real_escape_string", $users);
$users = implode(",", $users);
..("SELECT * FROM users_newest_post WHERE FIND_IN_SET(user, '$users')");
The FIND_IN_SET function is a but inefficient for this purpose. But you could transition to an IN clause with a bit more typing if there's a real need.
$sql = 'SELECT * FROM `users_newest_post` WHERE username IN (' . implode(',', $users) . ')';

Categories