PHP - Count SQL Results Per Day - php

So I have a table called Userswhich contains a table structure like this:
Lets say I have a mysql table called 'signups' with the following values:
UID|Name|Regdate
1|Admin|2014-03-04 10:51:01
2|Demo|2014-05-04 09:51:05
I want to create a graph showing how many people signed up in one day. I used this SQL Query:
SELECT DATE(regdate) AS `Date` , COUNT(*) AS Signups FROM `users` GROUP BY DATE(regdate)
It gave me an output of:
Date|Signups
2014-03-04|1
2014-05-04|1
I wanted the output in a PHP File so I made this
<?php include_once("inc/db.php"); ?>
<?php
$query ="
SELECT DATE(regdate) AS `Date`
, COUNT(*) AS Signups
FROM `users`
GROUP BY
DATE(regdate)
";
$query_params = array(
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
echo $result;
?>
When I try to access the page, the result I get should be same thing I got from the SQL Query. However the result I get is 1. As you can see, I am using PDO. I am a beginner please help me please. :)

Do you use mysqli or PDO? Anyway execute does not do the job of returning the eventual result, assuming you use PDO, you have to:
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
foreach($stmt->fetchAll() as $fetch)
{
// do something
}
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
echo $result;

Related

Is it possible to get data from the 2nd table using column in 1st table using PHP PDO?

Well, I have a situation that I need to SELECT data from two tables at once. But my main problem is how can I SELECT .. WHERE in my table2 when the value that I needed in WHERE clause is in the return value of SELECT statement in table1.
test.php
<?php
include("../../connection.php");
$data = json_decode(file_get_contents("php://input"));
$id= $data->id;
try{
$db->exec("SET CHARACTER SET utf8");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "
SELECT * FROM tblstudents WHERE studID=':id';
SELECT * FROM tblparents WHERE studNumber=':studNumber';
";
$statement = $db->prepare($sql);
$statement->bindValue(":id", $id);
$statement->bindValue(":studNumber", $studNumber);
$result = $statement->execute();
echo json_encode($result);
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
The studNumber value is in the tblstudents which will have a return value from SELECT statement.
Is it possible that I can get the studNumber value in the return value of SELECT statement when the SELECT statement of the tblparents is in the same sql query? Or is there another way around?
Hope I clearly explained my situation.
You need to use JOIN for get data from multiple tables. Try this query:
$sql = "SELECT * FROM tblstudents JOIN tblparents on
tblstudents.studNumber = tblparents.studNumber WHERE tblstudents.studID=:id;"
$statement = $db->prepare($sql);
$statement->bindValue(":id", $id);
$result = $statement->execute();

need to SELECT and show all entries written by specific user and count it

I need to SELECT and show all entries written by specific user and number of his/her total entries
<?php include 'helperl.php'; include 'dbconn.php';
$name=$_GET['id'];
$sql="SELECT * FROM entries WHERE writer_user LIKE '%$name%'";
$result=$conn->query($sql);
$num_entry= count($result);
echo "$num_entry";
?>
First the LIKE option that you did will get you all the name that contain $user
Your query should be like
SELECT nb
FROM (SELECT writer_user,count(*) as nb
FROM entries
WHERE writer_user=you_var
Group BY writer_user)
For getting all the entries of specific user
SELECT *
FROM entries
WHERE writer_user=you_var
u can do a join in one query to get the information you wanted but there will be a duplication in the count attribut.
exemple :
entrie count
entrie1 4
entrie2 4
entrie3 4
entrie4 4
hope i helped you.
you should use SQL COUNT function to do this (SQL COUNT function
)
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Your code can look like this
<?php
try {
$name = htmlentities(strip_tags($_GET['id']));
$sql = "SELECT COUNT(writer_user) as counter FROM entries WHERE writer_user LIKE '%$name%'";
// create pdf instance
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("SELECT COUNT(writer_user) as counter FROM entries WHERE writer_user LIKE '%name%'");
$stmt->bindParam('name', $name);
$stmt->execute();
$result = $conn->query($stmt)->fetchAll();
var_dump($result);
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
$conn = null;
?>

Moving Rows Between Tables in Joomla

I have been trying to create a PHP script that will periodically move "completed" rows from a table on my Joomla site to a different table. The query I wrote works just fine in PHPMyAdmin:
INSERT INTO my_calsgovdocs.sent_copy
SELECT * FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%';
DELETE FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%';
I attempted to translate it into some PHP code which could run inside Joomla, and I've pasted that code below. It returns an "Unexpected T_STRING" error which points to the line below which starts ->insert into, and it has now occurred to me that the script wouldn't work because "insert into" isn't a valid method name! So far I can't find an equivalent method to be used inside Joomla. This was my attempt at the code:
try
{
$db->transactionStart();
$query = $db->getQuery(true);
$query
->insert into($db->quoteName('sent_copy'))
->select('*')
->from($db->quoteName('entered_copy'))
->where($db->quoteName('Status') . ' LIKE ' . $db->quote('%Sent%') . ';')
->delete from($db->quoteName('entered_copy'))
->where($db->quoteName('Status') . ' LIKE ' . $db->quote('%Sent%'));
$db->setQuery($query);
$result = $db->execute();
$db->transactionCommit();
}
catch (Exception $e)
{
$db->transactionRollback();
JErrorPage::render($e);
}
Anyone have an idea how I can accomplish this inside Joomla? I'd prefer (as you may have noticed above) to do it in one transaction so that, if there's an error, I won't have a mess on my hands.
$db->setQuery allows being passed a query string as an argument instead of an object. See "preparing the query": https://docs.joomla.org/J1.5:Accessing_the_database_using_JDatabase
I've also suggested running two of these queries as part of the same transaction.
I unfortunately don't have a joomla installation handy to test this, please comment if you find it doesn't work.
try
{
$db->transactionStart();
$query = $db->getQuery(true);
$query1 = "INSERT INTO my_calsgovdocs.sent_copy
SELECT * FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%'";
$db->setQuery($query1);
$result1 = $db->execute();
$query2 = "DELETE FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%'";
$db->setQuery($query2);
$result2 = $db->execute();
$db->transactionCommit();
}
catch (Exception $e)
{
$db->transactionRollback();
JErrorPage::render($e);
}
You could try doing it in plain old php? Something like
$conf = JFactory::getConfig(); // load your config
try{
$link = mysqli_connect($conf->get('host'), $conf->get('user'),
$conf->get('password'), $conf->get('db'));
mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_WRITE);
mysqli_query($link, "INSERT INTO my_calsgovdocs.sent_copy
SELECT * FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%'");
mysqli_query($link, "DELETE FROM my_calsgovdocs.entered_copy
WHERE `Status` LIKE '%Sent%'");
mysqli_commit($link);
}
catch (Exception $e)
{
mysqli_rollback($link);
JErrorPage::render($e);
}
mysqli_close($link);

LIKE query in PDO not working

PDO queries run fine, but when i try to use LIKE query it don't work and give error. i know i am doing something wrong, please if anyone can point out where i have gone wrong and how to run the the LIKE query properly.
<?php
/**
* Created by PhpStorm.
* User: HaiderHassan
* Date: 9/3/14
* Time: 9:52 PM
*/
header('Access-Control-Allow-Origin: *');
try {
$conn = new PDO('mysql:host=localhost;dbname=houserentsystem;charset=utf8', 'root', 'admin');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($_POST['searchFilter']){
$searchFilter = "%".$_POST['searchFilter']."%";
echo $searchFilter;
$stmt = $conn->query("SELECT roomName FROM roomnames WHERE roomName LIKE".$searchFilter);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
print_r(json_encode($results));
}
i have two columns in table(roomnames) roomID and roomName
i want to get the result of data which matches with the posted value.
You have multiple problems:
a) Vulnerable to SQL injection attacks
b) Lacking a space after LIKE, which means you're producing
... LIKE%foo%
c) Lack of quotes around your search parameter, so even if you did fix b), you'd still have a problem. it should be
... LIKE '$searchParameter'
^----------------^--- note the quotes
The statement should be prepared
if($_POST['searchFilter']){
$searchFilter = $_POST['searchFilter'];
echo $searchFilter;
try {
$conn = new PDO('mysql:host=localhost;dbname=houserentsystem;charset=utf8', 'root', 'admin');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT roomName FROM roomnames WHERE roomName LIKE ?");
$stmt->execute(array('%'.$searchFilter.'%'));
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//print_r($results);
echo json_encode($result);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
In this line:
$stmt = $conn->query("SELECT roomName FROM roomnames WHERE roomName LIKE".$searchFilter);
There has to be a space behind the LIKE
You need to enclose the string between apostrophs to make it an actual SQL string
You should definitely use parametrized queries, because right now this is a gaping SQL injection hole (what if someone searches for ';delete from roomnames; select '?)

Array to integer conversion in sql using php pdo

If I execute the below code i am getting a array value...what i have to do to get a integer value. I need the number given in the dislikes value for that particular image
$sql1="SELECT dislikes FROM photo where imagename=:id";
$q1=array(':id'=>$id);
try
{
$stmt = $pdo->prepare($sql1);
$stmt->execute($q1);
$stmt->setFetchMode(PDO::FETCH_BOTH);
$result= $stmt->fetch();
}
catch (PDOException $e)
{
die("Failed to run query: " . $e->getMessage());
}
print_r($result);
Probably doing a SELECT count(dislikes) is the best option. Or maybe using a for loop in $result to sum the dislikes
If there are more than a single entry in the database, the query will return an array.
Try:
SELECT count(dislikes) FROM photo where imagename=:id
So you'll get an interger, which is the amount of entries in database.
If I use
$result= $stmt->fetcholumn();
instead of
$result= $stmt->fetch();
..THANKS FOR EVERYONE WHO HELPED ME..BUT YOUR SUGGESTIONS ARE NOT PERFECT

Categories