sql in database gives different result in php - php

I got the following sql:
SELECT COUNT(pu_id) FROM purchasing WHERE MONTH(pu_create_date)=MONTH(NOW())
In Mysql it gives the result 0 as expected.
When I put it in PHP I get the result 1 of $numMonth. This is the php code:
$database = new Database();
$db = $database->getConnection();
$stmt= $db->query('SELECT COUNT(pu_id) FROM purchasing WHERE MONTH(pu_create_date)=MONTH(NOW())') ;
$numMonth = $stmt->execute();
echo $numMonth;
Why do I get two different results?
pu_id = unique key
pu_create_date = timestamp

You have to fetch the row from the query.
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_NUM);
$numMonth = $row[0];
echo $numMonth;

Related

How do I count the number of rows in a MySQL Table?

I know that inside MySQL, you can use:
SELECT COUNT(*) FROM table
I have written the following code in PHP to display the number of rows on the page:
$sql = 'select * from users';
$data = $conn -> query($sql);
echo $data;
But when I run it, I get the following error:
Catchable fatal error: Object of class PDOStatement could not be converted to string in [Directory] on line 19.
I think the problem is that the returned value is not in string form. If that is correct, how would I be able to display the number of rows on the page?
If you want to count the rows you can do this with PDO:
$sql = 'select * from users';
$data = $conn->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);
Well, you arent badly off, you are almost there:
$sql = 'SELECT COUNT(*) as numrow FROM users';
$data = $conn -> query($sql);
rows = $data->fetchAll();
Depending on the type of return data, you could use
$rows->numrow if the return data is an object
There are some easy and faster way to do this
COUNT the column in query and fetch
$sql = "SELECT COUNT(id) AS total_row FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
echo $count['total_row'];
Using rowCount()
$sql = "SELECT * FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;

printing the value of a query using php

I'm trying to print out the value of a query but what appears on the screen is the query itself!
mysql_select_db($database_databasestudents, $databasestudents);
$result = mysql_query("Select name from country where id = '$s';",$databasestudents);
$r = mysql_fetch_array($result) ;
echo $r;
where $s is an integer
This is what I get on the screen:
SELECT name FROM country WHERE id='3'
3 is the value of $s
You need to run the query first
http://www.php.net/manual/en/mysqli.query.php
and then loop though the results
http://www.php.net/manual/en/mysqli-result.fetch-array.php
You need to run the query in order to get the result. Maybe this will get you started:
$pdo = new PDO('mysql:host=YOURHOST;port=YOURPORT;dbname=YOURDB', 'YOURUSER', 'YOURPASSWORD');
$sql = 'SELECT name FROM `country` WHERE id=?';
$stmt = $pdo->prepare($sql);
$stmt->execute(array($s));
while ($result = $stmt->fetchObject())
{
echo $result->name;
}
$r is an array, not a string. You need print_r($r); or var_dump($r);, not echo
You have created a string containing your query.
You must instantiate a database connection and then execute your query.

PHP SQL: Find smallest value using PDO

I am attempting to find the smallest value in my SQL records using a PDO connection. The records are varchar so must be converted to int in order to find smallest. I am stuck on this issue:
mysql_fetch_assoc() expects parameter 1 to be resource, array given
The problem is I do not know how to get a resource from a PDO connection. The query is valid.
<?php
//load and connect
require("config.inc.php");
//change varcar to ints and put into array
$query = "SELECT score FROM easy";
$stmt = $db->prepare($query);
$result = $stmt->execute();
$rows = $stmt->fetchAll();
$scoreArray = array();
$index = 0;
while($row = mysql_fetch_assoc($rows)){
$scoreArray[$index] = intval($row);
$index++;
}
$smallest = min($scoreArray);
$response["success"] = 0;
$response["message"] = "The min is: ".$smallest;
echo(json_encode($response));
?>
You need to convert your field to int.
find smallest value by means of SQL:
SELECT min(score) FROM easy
While selecting all the records from database and process them in PHP is NOT the way to go. It's against the very basic principles. Data mining is a job for database.
$query = "SELECT min(score) FROM easy";
$stmt = $db->prepare($query);
$result = $stmt->execute();
$min = $stmt->fetchColumn();
Don't use mysql_fetch_assoc when using PDO:
Replace
while($row = mysql_fetch_assoc($rows)){
with
foreach ( $rows as $row ){

Count number of rows in SQL database

I am trying to view how many rows there are based on a SQL query using PHP.
I seem to be able query the database and return fields from a row but can't seem to find out how many rows there are based on the same query.
<?php
$host = 'localhost';
$user = 'MyUsername';
$pass = 'MyPassword';
$database = 'MyDatabase';
$con=mysqli_connect($host,$user,$pass ,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
mysqli_close($con);
?>
All it returns is the text Rows on the screen, without the number of rows at the start.
Like I said, this same query works and returns a value if I try and select a row using:
while($row = mysqli_fetch_array($result))
{
echo $row["test"];
}
Anyone know why it won't return the number of rows?
You are using MySQLi. Because of you don't have a mysql query, mysql_num_rows doesn't return desired value.
You have to replace your mysql function with mysqli equal:
$num_rows = mysqli_num_rows($result);
You are using Mysqli to you should use mysqli_num_rows
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysqli_num_rows($result);
If you want only count then you can directly use count(*) like this:-
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result;
I'll do some thing like this:
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result

Count rows in mysql with php when have specific string

I have a table in my database named visitor_table . Within table i have a column named visitor_affiliate. I want to get the count of the rows when visitor_affiliate = "someurer" .
I want to get the count as number. I already have this code but i don't know how to get the count only for the rows containing the string. I currently get the number of all rows,
$result = mysql_query("SELECT * FROM visitor_table");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
You can ask MySQL to return the count:
SELECT COUNT(*) FROM visitor_table WHERE visitor_affiliate = 'someurer'
You shouldn't be using the ancient (deprecated as of PHP v5.5.0, soon to be removed entirely) MySQL extension for writing new codeā€”use instead the improved MySQLi extension or the PDO abstraction layer, both of which enable you to pass variables to the database in a safe, parameterised, fashion that ensures they are not evaluated for SQL (and therefore prevents SQL injection attacks):
$dbh = new PDO("mysql:dbname=$dbname", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$qry = $dbh->prepare('
SELECT COUNT(*) FROM visitor_table WHERE visitor_affiliate = ?
');
$qry->execute(['someurer']);
echo $qry->fetchColumn(), ' rows';
$result = mysql_query("SELECT * FROM visitor_table WHERE `visitor_affiliate` = 'someurer'");
$num_rows = mysql_num_rows($result);
echo $num_rows . " Rows\n";
With what little information you have given just try this-
$result = mysql_query("SELECT * FROM visitor_table Where visitor_affiliate like '%someurer%'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
The deprecated MySQL:
$res = mysql_query('SELECT * FROM visitor_table');
echo 'Number of rows:'.mysql_num_rows($res);
Procedural MySQLi:
$tu = mysqli_prepare($DBH,'SELECT * FROM visitor_table');
mysqli_execute($tu);
$num_rows = mysqli_num_rows($tu);
echo $num_rows.' rows\n';
mysql has been deprecated. Please use mysqli.
Using MySQLi bind_param to get your result:
$someuser = 'Dave';
$DBH = mysqli_connect('localhost','user','pass','database');
$query = mysqli_prepare($DBH,'SELECT * FROM visitor_table WHERE user = ?');
mysqli_bind_param($query,'s',$someuser);
mysqli_execute($query);
mysqli_bind_result($id,$user,$tabCol1,$tabCol2);
while(mysqli_fetch_result){
$row = $row +1;
echo $user.': was found in the record with ID of: '.$id;
}
echo 'total records found:'.$row;
That's one way of doing it as I'm not completely 100% sure about using a mysqli_num_row() with the query above.

Categories