Updating with random data fails for php pdo - php

I am trying to update my table with a randomly generated data field with this script
for($i = 0; $i < 10 ; $i++){
$date = rand(1,30).'/'.rand(1,12).'/'.'15';
$dbh = new PDO('mysql:host=localhost;dbname=qp', 'root', '123456');
$sth2 = $dbh->prepare("update r_data set the_date = '$date' where transaction_type = 'send'");
echo $date.'<br/>';
$sth2->execute();
}
but the field is only updated with only one random string i.e 18/5/15 but the variable $date has generated random dates as i want.
Why is the date field not being updated with random data?.

You are updating the same row(s) each time. Once the loop is done, you'll only see the last 'random' value in the database, as all preceding values will have been replaced.
You'll have to qualify the rows your are updating to be different each iteration of your loop if you want to see different dates for different rows.
Alternatively, have MySQL insert random dates for you:
update r_data set
the_date = DATE '2015-01-01' + INTERVAL FLOOR(RAND() * 365) DAY
where transaction_type = 'send'
This'll insert a different random date value for each selected row; no loop required.

Related

Adding days to a Date (retrieved from MySQL database) in PHP

I am trying to do, what I assume is, an easy task of adding days to a date.
I have a date stored in a MySQL table, in a column called meta_date, with the type of DATE (A date, supported range is 1000-01-01 to 9999-12-31)
I retrieve this date from the database as follows:
$thisId = 1;
$dateQuery = mysqli_query($connection, "SELECT * FROM `sometable` WHERE `id` = '$thisId'");
$fetchDate = mysqli_fetch_assoc($dateQuery);
$theDate = $fetchDate['meta_date'];
Now I add a number of days to this date.
$newDate = date("Y-m-d", strtotime($theDate . " + 7 days"));
Next I put it back inside the database with an UPDATE query.
$editDate = mysqli_query($connection, "UPDATE `sometable` SET `meta_date` = '$newDate' WHERE `id` = '$thisId'");
However the date always returns as 0000-00-00 after the update.
Am I missing something here to do with the way the date is handled in PHP?
edit: The data I first retrieve from the database (into $theDate) is "2016-11-30".
You can use Mysql's built in function DATE_ADD()
Syntext
DATE_ADD(date,INTERVAL expr type) Where date is a valid date expression and expr is the number of interval you want to add.
For your case
UPDATE sometable
SET `meta_date` = DATE_ADD(`meta_date` , INTERVAL 7 DAY)
WHERE `id` = '$thisId';

Mysql query for sorting Time in hms format

I am trying to sort the data in Mysql descendingly based on the time for videos.
I have Video_Duration column in my database in which I store the time for videos in hms format( For example 1h54m3s, 9m3s, 0m3s).
When i try to sort the database using the query below I am getting the output like 9m0s, 9m0s first instead of time with more time(like 1h35m29s).
I am using the following query to sort the database
$sql = "select * from videos where Category_Name='$category' ORDER BY Video_Duration DESC limit 50";
Can you guys help me solve the problem
Unfortunately your data is saved into the database not in the best way.
A varchar is sortable but follows the rules of alphabetical order. For example if I want to order the first 12 numbers with:
SELECT TOP 12 value
FROM number_in_order
ORDER BY value ASC
I will obtain something like this:
0
1
10
11
2
3
4
5
6
7
8
9
that is wrong.
The correct way to handle the length of your video files is using an INT field to store the amount of seconds and THEN via php retrive the value and format it in a user-readable way.
What I will suggest now is to create a new column called "NEW_VIDEO_DURATION" that will be a INT, then using a simple routine in PHP that read data from the varchar column, populate the new one with the correct value in seconds.
You can do something like this to parse your string value:
$stringValue = "1h3m40s";
$h = 0;
$m = 0;
$s = 0;
$splitted = $stringValue.split("h");
if($splitted.length > 0){
$h = $splitted[0];
$splitted = $splitted[1].split("m");
}else{
$splitted = $splitted[0].split("m");
}
$m = $splitted[0];
$s = $splitted[1];
$intValue = ((($h * 60) + $m) * 60) + $s;
Now inside the var $intValue you have the correct time in seconds that can be stored inside the new column in the database.
Once you've converted all the values you can delete the old column as:
ALTER TABLE table_name
DROP COLUMN video_duration
And rename the new column in:
ALTER TABLE table_name
RENAME COLUMN new_video_duration to video_duration
And you're done.
cheers

Check which table has the result in MySQL query, using PHP?

I am using the following MySQL query to check several tables for any results where the date is within 30 days.
What I want to do is be able to also check which table had the result, not just whether the MySQL query found a result in general.
One of my tables is supplier_bank_details, so if there is a record in this table with a date which is less than 30 days old then I am echoing out bank detail information, otherwise if it's my other table supplier_invoices then I want to echo out invoice information.
Here's what I have so far but I am really new to MySQL and struggling a bit. Please could someone show me what I would need to do to get this to work.
<?php require_once 'config.php'; ?>
<?php
$tbl_name = 'supplier_bank_details';
$tbl_name2 = 'supplier_invoices;
$query = "select * from $tbl_name, $tbl_name2 WHERE date > NOW() - INTERVAL 30 DAY ORDER BY date DESC";
$result = mysql_query($query) or die( mysql_error() );
$row = mysql_fetch_assoc($result);
if(mysql_num_rows($result) > 0) {
$datetime1 = new DateTime(); // Today's Date/Time
$datetime2 = new DateTime($row['date']);
$interval = $datetime1->diff($datetime2);
if(mysql_num_rows($tbl_name) > 0) {
$account_number = '****'.substr($row['account_number'], -4);
echo '<div class="contracts_area"><div class="table_header"></div>';
echo '<div class="request"><p>Bank Details Changed</p><p>'.$row['sort_code'].'</p><p>'.$account_number.'</p><p>about '.$interval->format('%d days ago').'</p></div>';
echo '</div>';
}else{
some invoice info here
}else{
echo '<div class="no_activity">No Recent Activity</div>';
}
}?>
Not too elegant, but you can add a constant field to your query, which refers to the table name:
select *,"tab1" as tablename from tab1
A column, called tablename will appear, wit with value of "tab1" in each row. It works only if there is least one record in the table.
Update: it's more useful, when you join different tables into a single result set.
Use separate queries if the data from both tables doesn't need to be merged together. Have one function to get supplier_bank_details over the last x days, another to get supplier_invoices over the last x days, and then you can handle any logic about what you want to show in PHP.

MySQL & PHP: summing up data from a table

Okay guys, this probably has an easy answer but has been stumping me for a few hours now.
I am using PHP/HTML to generate a table from a MySQL Table. In the MySQL table (TimeRecords) I have a StartTime and EndTime column. In my SELECT statement I am subtracting the EndTime from the StartTime and aliasing that as TotalHours. Here is my query thus far:
$query = "SELECT *,((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date
BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
ORDER BY Date
";
I then loop that through an HTML table. So far so good. What I would like to do is to add up all of the TotalHours and put that into a separate DIV. Any ideas on 1) how to write the select statement and 2) where to call that code from the PHP/HTML?
Thanks in advance!
Try this
$query= "
SELECT ((EndTime - StartTime)/3600) AS Hours, otherFields, ...
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31' ";
$records =mysql_query($query);
$sum= 0;
while($row=mysql_fetch_array($records))
{
echo"$row['otherFields']";
echo"$row['Hours']";
$sum+=$row['Hours'];
}
echo" Total Hours : $sum ";
Just use a single query with a Sum(). You could also manually calculate it if you're already displaying all rows. (If paginating or using LIMIT, you'll need a separate query like below.)
$query = "
SELECT Sum(((EndTime - StartTime)/3600)) AS SumTotalPeriodHours
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31'
";
You can do this in the same query if you have a unique id using GROUP BY WITH ROLLUP
$query = "
SELECT unique_id,SUM((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
GROUP BY unique_id WITH ROLLUP
ORDER BY Date
";
In this instance the last result from your query with contain NULL and the overall total. If you don't have a unique ID you will need to do it in PHP as per Naveen's answer.
A few comments on your code:
Using SELECT * is not considered good practice. SELECT the columns you need.
Not all months have a day 31 so this may produce unexpected results. If you're using PHP5.3+, you can use
$date = new DateTime();
$endDate = $date->format( 'Y-m-t' );
The "t" flag here gets the last day of that month. See PHP docs for more on DateTime.

MySQL - Blog post scheduling system

I am creating a blog post scheduling system using CodeIgniter. I want 10 posts to show up a day. There is a field in the posts table named scheduled_date which I will get the posts that are less than or equal to the current date. When an admin user adds a new record to the database, I need an SQL statement that somehow will help me COUNT the number of records with the latest date in the database. For example:
// 9 records returned for the date 2011-01-01
$numbers_of_records == 9;
if($numbers_of_records == 10){
// inserts record with `scheduled_date`='2011-01-01'
}else{
// inserts record with the date latest date +1 day
}
How would I efficiently accomplish this?
Thanks
This will do the trick. It is simple and efficient.
<?php
// It is very bad to have floating values, especially for settings
// it is good to use some sort of factory or settings class
$maxDailyPosts = (int) SettingsFactory::getSettings()->get('maxDailyPosts');
$date = '2011-01-01';
// Load # of post for data
$numberOfRecords = (int) getNumberOfPostPerDate($date);
// Figure out the interval for increment
$dayInterval = ($numberOfRecords >= $maxDailyPosts ) ? 1 : 0;
//
$query = "INSERT INTO tbl (publish_date, ...) VALUES (DATE_ADD('$date', INTERVAL $dayInterval DAY), ...)";
?>

Categories