The total number of mysql results not displaying properly - php

I am working on a total page view system and each time someone visits a page it adds the current data and their ip address. When I go to display the total number of rows on a particular day the site just displays 'Rows' without the number.
Code:
<?php
$servername = "";
$username = "";
$password = "";
$dbname = "";
$date = date("Y-m-d-h-m-s");
$ip = $_SERVER['REMOTE_ADDR'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$date = date("Y-m-d");
$result = mysqli_query("SELECT FROM page_views WHERE date = $date");
$num_rows = mysqli_num_rows($result);
echo "$num_rows Rows\n";
$conn->close();
?>
Could someone please indicate what is going wrong.

Your query is failing but you don't know it because you don't check for errors. If you did you would see a syntax error due to you omitting the * from your SELECT clause and your date not being in quotes.
Change:
$result = mysqli_query("SELECT * FROM page_views WHERE date = $date");
to:
$result = mysqli_query("SELECT * FROM page_views WHERE date = '$date'");

Related

How to update data when the expiration time ends

I have build an apps with Codeigniter and want to make cron job and use MySQL
i have a table 'order' and have field like this
order_id | order_expired_date
001 | 2018-11-12 10:03:33
and i have table 'order_payment' like this,
order_id | op_status
001 | pending
I have many fields in these two tables but only include those that have something to do with this question
i have code from php but not in model codeigniter
$result = mysql_query('UPDATE `'order_payment'`
SET op_status='expired'
WHERE
(UNIX_TIMESTAMP( now( ) ) - `order_expired_date`));
The question is how to change the status in the order_payment table to expire when the expiration time is up?
You may use following code, you need to modify code as per your requirements..
<?php
$servername = "xyz";
$username = "xyz";
$password = "xyz";
$dbname = "xyz";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
$sql = "SELECT *,o.`order_id` as `oid` FROM `order` as o,`order_payment` as op WHERE o.`order_id`=op.`order_id` AND op.`op_status`='paid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$today = date('Y-m-d');
$expDt = date('Y-m-d',strtotime($row['order_expired_date']));
if($today==$expDt){
$updCltSql = "UPDATE `order_payment` SET `op_status`='expired' WHERE `order_id`='".$row['oid']."'";
$conn->query($updCltSql);
}
}
}
$conn->close();
?>
We always prefer core-php file as cron-job..
After plenty of research, this is what I came up with - hope it helps. In your example, I don't think you need to put single quotes around the table name order_payment, unless that is something unique to CodeIgniter.
$orderID = mysql_query("SELECT order_id FROM order"); // Get order IDs of order table, assuming it has the same list of order IDs as the order_payment table
$order_ids = array(); // Put in array
while ($row = mysql_fetch_array($orderID)) {
$order_ids[] = $row['order_id'];
}
foreach ($order_ids as $order_id) { // Iterating through order_id's of array in order to read same index/row number from both tables
$expirationDate = mysql_query("SELECT order_expired_date FROM order WHERE order_id='$order_id'");
$expire = date('M j Y g:i A', $expirationDate); // Converting MySQL timestamp to correct format for strtotime
$today = strtotime("now");
if($today >= $expire) // If past the expiration date
mysql_query("UPDATE order_payment SET op_status='expired' WHERE order_id='$order_id'");
}

trying to UPDATE SQL after one SQL

I am calculating AGE by DATE from DOB field, then I want to push it into AGE with correct age based on DOB . So As I debug The DOB calculating to AGE is works, but it cannot update AGE the code:
<?php
$servername = "localhost";
$username = "usernameexmaple";
$password = "passworking";
$dbname = "dbnameworking";
// Create connection
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id as ID, YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)) as age
FROM regio_users";
$sql2 = ("UPDATE regio_users SET age = '$newage' WHERE id ='$newid' ");
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$newage = $row['age'];
$newid = $row['ID'];
$sql2 = ("UPDATE regio_users SET age = '$newage' WHERE id ='$newid' ");
$result2 = $conn->query($sql);
if ($result2){
echo "done"."<br>";
}
}
}
else {
echo "0 results";
}
$conn->close();
?>
It echos DONE for every ID but not updating anything at all.
You have used $result2 = $conn->query($sql); which is incorrect. You have to use $result2 = $conn->query($sql2); as $sql2 is the new query you formed.
This can be done with a single line SQL, rather than using PHP to loop through all the rows to only update the age:
UPDATE `regio_users` SET `age` = YEAR(CURRENT_TIMESTAMP) - YEAR(`dob`) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(`dob`, 5));
As saty pointed, use correct variable name.
Check if autocommit is on. If not, make sure you commit the data. Check for its syntax in PHP.

php sql How to display only the last value in the row?

I need only to display the last values in the row. Now its displaying
Message for: Rocha : gff
Message for: Rocha :
Message for: Rocha : hi my name is kenny
I only need it to display Message for: Rocha : hi my name is kenny.
Thank you
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "company";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, className, lastname, messages FROM Mymesages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if("CPS210-CompSci-I (4)"==$row["className"] && $lastname== $row["lastname"]){
echo "Message for: " . $row["lastname"]. " : " . $row["messages"]. "<br>";
}
}
}
$conn->close();
?>
If you're looking for only one record, that too the last one, you just need to modify your query a little. Also, there's no need for the loop in that case.
$sql = "SELECT id, className, lastname, messages FROM Mymesages ORDER BY id DESC LIMIT 1";
Replace this line:
while($row = $result->fetch_assoc()) {
With simply:
$row = $result->fetch_assoc();
If you want to display the last row, then your query should be like this:
$sql = "SELECT id, className, lastname, messages FROM Mymesages ORDER BY id DESC LIMIT 1";
And later, instead of while loop simply fetch the row like this:
$row = $result->fetch_assoc();

Trying to display values from a SQL table, recieveing error, trying to get property of non-object

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "comp4";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT OrderID, id, items FROM orders WHERE id= $user";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$results = $row["OrderID"]. " " . $row["id"]. $row["items"]. "<br>" ;
}
$loop = implode( " ", $items );
echo $loop;
}
?>
So, I have this code and I'm trying to display OrderID, id and items from the user thats logged in $user=whoever's logged in that's in a different part of my code, however I keep getting an error
Notice: Trying to get property of non-object in C:\xampp\htdocs\myorders.php on line 35
After looking around, I'm still not quite sure how to fix this. Any help is appreciated
I'm guessing your error lies in this line of code:
$sql = "SELECT OrderID, id, items FROM orders WHERE id= $user";
It could be that ID is a reserved keyword of SQL, or that $user is undefined and/or not a numeric value.
Try the following:
$sql = "SELECT `OrderID`, `id`, `items` FROM `orders` WHERE id = $user";
The reason for the error is your query fails. Then you later do the following:
if ($result->num_rows > 0) {
And since the query failed, $result is not an object, and you try to access num_rows of this non-object.
Of course I am only guessing because we need more information :)

Using Highcharts with mysql for Page Visits

I am trying to use Highcharts to display user visits per property, however I am unsure how to set up the SQL query to properly display this. It would be a lot easier if our database simply listed page visits during specific periods of time, but it's stored per-user, per-property, per visit, as you can see here:
I know that I have to query the sum visits per property and sort it by month, but exactly the best way to do this is beyond me. This what I've got so far:
<?php
$con = mysql_connect('localhost', 'root', 'root');
if (!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db('demeure', $con);
//$date_start = $_POST['date_start'];
//$date_end = $_POST['date_end'];
$date_start = '2012-07-01 00:00:00';
$date_end = '2012-08-01 00:00:00';
$result = mysql_query("
SELECT
COUNT(id) AS count,
created_at
FROM
user_property_visits
WHERE
created_at BETWEEN '$date_start' AND '$date_end'");
while ($row = mysql_fetch_array($result)) {
echo $row['count'] . "\t" . $row['created_at']. "\n";
}
mysql_close($con);
?>
This results with a blank page. I'm not sure how close I am to getting what I need, but thanks for the help.
I'm not sure if you want this, but you can filter the period in the WHERE clause. Check if it could help:
<?php
// Show all PHP errors.
error_reporting(E_ALL);
// Connect with MySQL
$con = mysql_connect('localhost', 'your_user', 'your_password');
if (!$con) {
die('Could not connect: '.mysql_error());
}
mysql_select_db('demeure', $con);
// Obtain date range from $_POST or
// manually edit this.
//$date_start = $_POST['date_start'];
//$date_end = $_POST['date_end'];
$date_start = '2012-07-20 20:30:00';
$date_end = '2012-07-20 20:37:00';
// Query with GROUP BY
$result = mysql_query("
SELECT
COUNT(id) AS `count`,
created_at
FROM
user_property_visits
WHERE
created_at BETWEEN '$date_start' AND '$date_end'
GROUP BY
created_at");
while ($row = mysql_fetch_array($result)) {
echo 'Count: ' . $row['count'] . '<br/>' . 'Group by date: ' . $row['created_at'] . '<br/>';
}
// With the schema used in SQL Fiddle, this code will reproduce
//
// A PHP Error was encountered
// Severity: 8192
// Message: mysql_connect(): The mysql extension is deprecated and
// will be removed in the future: use mysqli or PDO instead
//
// Filename: views/home.php
//
// Line Number: 7
//
// Count: 4
// Group by date: 2012-07-20 20:36:28
mysql_close($con);
?>
Using this, you can use a datepicker, for example, to select the date range and obtain this values via POST (ajax).
Check this SQL Fiddle
I was able to solve it with the following:
<?php
$host = "localhost";
$user = "root";
$pass = "root";
$database = "demeure_new";
$dsn = "mysql:dbname=$database;host=$host";
$pdo = new PDO($dsn, $user, $pass);
$query = "SELECT DAY(created_at) AS day, MONTH(created_at) AS month, YEAR(created_at) AS year, count(user_id) AS count FROM user_property_views GROUP BY day";
$stmt = $pdo->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
$newArray = array();
foreach($result as $r)
$newArray[$r["year"]][$r["month"]][$r["day"]] = $r["count"];
//print_r($newArray);
json_encode($result, JSON_NUMERIC_CHECK);
echo json_encode($newArray);
?>

Categories