This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 5 years ago.
<?php
//Connection Variable to establish connection to the database parameters and localhost, user, password
$connection = mysql_connect("localhost","root","") or die(mysql_error());
//selects the database called trial and uses the connection details
mysql_select_db("bb",$connection);
//Checks to see if a file has been submitted
if(isset($_POST['submit'])){
// if submitted
/*Propriety Information if user needs to be added*/
/*
$gym=mysql_real_escape_string($_POST['Gym']);
$access=mysql_real_escape_string($_POST['accessID']);
$Chal=mysql_real_escape_string($_POST['Chal']);
*/
//Files path with the added extention of a random name at the end.
$file=$_FILES['file']['tmp_name'];
echo $file;
//Force Open the file in read state
$handle = fopen($file, "r");
fgetcsv($handle,1000,",");
fgetcsv($handle,1000,",");
fgetcsv($handle,1000,",");
//initates a check for the csv
if(($filedata =fgetcsv($handle,1000,",")) !== false )
{
//While loop with the ammount of data in the csv, fgetcsv grabs all the data that is open. Each cell is restricted to 1000 charachters, then seperated by a comma
while(($filedata =fgetcsv($handle,1000,",")) !== false )
{
//Cycles through the row and each cell is then put into an array
// Multidimensional array tutorial E- Excel, DBS - Database
$userIDP2 = $filedata[0]; // E 1. User ID , DBS - userid
$height = $filedata[1]; // E 2. Height, DBS - height
$genderIdentifier = $filedata[2]; // E 3. gender, DBS - gender (UserTable)
$testDateChange = $filedata[4]; // E 5. Test Date / Time, DBS - testDate
$weight = $filedata[5]; // E 6. Weight, DBS - weight
$bodyFatMass = $filedata[23]; // E 24. BFM (Body Fat Mass), DBS - bodyFatMass
$SkeletalMuscle = $filedata[32]; // E 33. SMM (Skeletal Muscle Mass), DBS - SkeletalMuscle
$bodyFatP = $filedata[38]; // E 39. BFP (Body Fat Percentage), DBS - bodyFatP
$lean_RA = $filedata[62]; // E 63. LM of Right Arm, DBS - lean_RA
$lean_LA = $filedata[64]; // E 65. LM of Left Arm, DBS - lean_LA
$lean_Trun = $filedata[66]; // E 67. LM of Trunk (Abdomin), DBS - Lean_Trun
$lean_RL = $filedata[68]; // E 69. LM of Right Leg, DBS - lean_RL
$lean_LL = $filedata[70]; // E 71. LM of Left Leg, DBS - lean_LL
$wc_TargetW = $filedata[73]; // E 74 Target Weight, DBS - wc_TargetW
$BMR = $filedata[77]; // E 78.BMR, DBS - BMR
$visceralFat1 = $filedata[81]; // E 82.Visceral Fat Level, DBS - visceralFat
/*Replaces specific characters strings for the associated data */
$userIDR2 = str_replace("<","",$userIDP2);
$userID = str_replace(">","",$userIDR2);
$visceralFat = str_replace("level","",$visceralFat1);
$HyphenDate = str_replace('.','-' , $testDateChange);
$date = DateTime::createFromFormat('d-m-Y H:i:s', $HyphenDate);
echo $date->format('Y-m-d h:i:s');
echo $date;
//Variable Declare
$Gender ='';
// To check if Male or Female
if($genderIdentifier == 'M' || $genderIdentifier == 'm'){
$Gender = "Male";
}else if($genderIdentifier == 'F' || $gender == 'f'){
$gender = "Female";
}else{
$gender = "intermittent";
}
//Change the Date Time format
echo"<br/>";
//sql query
$sqlBodyCompositionStart="
INSERT INTO `bodycomp`
(
`userid`,
`height` ,
`testDate` ,
`weight`,
`bodyFatMass`,
`SkeletalMuscle`,
`bodyfatP`,
`lean_RA`,
`lean_LA`,
`lean_Trun`,
`lean_RL`,
`lean_LL`,
`wc_TargetW`,
`BMR`,
`visceralFat`
)VALUES (
'".$userID."',
'".$height."',
'".$testDate."',
'".$weight."',
'".$bodyFatMass."',
'".$SkeletalMuscle."',
'".$bodyFatP."',
'".$lean_RA."',
'".$lean_LA."',
'".$lean_Trun."',
'".$lean_RL."',
'".$lean_LL."',
'".$wc_TargetW."',
'".$BMR."',
'".$visceralFat."'
);";
$sqlBodyCompositionEnd="
INSERT INTO `bodycomp`
(
`height_1` ,
`testDate_1` ,
`weight_1`,
`bodyFatMass_1`,
`SkeletalMuscle_1`,
`bodyfatP_1`,
`lean_RA_1`,
`lean_LA_1`,
`lean_Trun_1`,
`lean_RL_1`,
`lean_LL_1`,
`wc_TargetW_1`,
`BMR_1`,
`visceralFat_1`
)VALUES (
'".$height."',
'".$testDate."',
'".$weight."',
'".$bodyFatMass."',
'".$SkeletalMuscle."',
'".$bodyFatP."',
'".$lean_RA."',
'".$lean_LA."',
'".$lean_Trun."',
'".$lean_RL."',
'".$lean_LL."',
'".$wc_TargetW."',
'".$BMR."',
'".$visceralFat."'
);";
// Check for user name
$userNameSQL ="SELECT *
FROM user
WHERE username ='".$userID."'";
$userCheck = mysql_query($usernameSQL) or die(mysql_error());
if(mysql_num_rows($userCheck)==1) //If rows are return
{
$sqlBodyCompositionEnd;
$uploadData = mysql_query($sqlBodyCompositionEnd) or die(mysql_error());
if($uploadData)
{
echo"Data has uploaded";
}
else
{
echo "Data has not been uploaded";
}
}
else
{
// Adds a new User
// SQL Query
$sql =" INSERT INTO `user`(`UserName`,`gender`,)
VALUES
('".$userID."','".$gender."')";
$userID = mysql_insert_id();
$resultNA = mysql_query($sql) or die(mysql_error()); //run your SQL query
if($resultNA)
{
echo"A new User has been added";
// Once a new user has been added, it then tried to add data
$sqlBodyComposition;
$uploadData = mysql_query($sqlBodyCompositionStart) or die(mysql_error());
if($uploadData)
{
echo"Data has uploaded";
}
else
{
echo "Data has not been uploaded";
}
}
else
{
echo "There is no user";
}
}
}
}
}
/*
OBJECTIVE FOR FILE:
This file grabs the file that was posted and cycles the data in the csv; to avoid duplication of pages, the bottom half the code should check to see if an existing
user is there; if it is, it uses the same code that would be used if the listed memeber wasn't in the database. This means that $sqlBodyComposition should be a
universal variable which will limit duplication.
We need to create a function that checks for a user, returns true and inserts the
$sqlBodyComposition query. If a user doesn't exist, we need to remove "<" and ">"
in the ID insert a new user. When the user is inserted, it is to then insert that
data about the body composition to the user.
It is to return to a page and determine whether it succeeded or not.
*/
?>
So I have a date in a csv file and I need php to convert it to a more appropriate format which is Y-m-d h:i:s
the format I need to convert
10.05.2017 18:31:07
this is stored as a variable/string
I've used str_replace('.','-',$date);
and I now need to reverse the Year and Date to achieve the submit-able format
is it possible to grab some help with this?
It would probably be easier to create a date object rather than rearranging the string.
This code should work for what you want to do:
<?php
//Raw Input as string
$raw = "10.05.2017 18:31:07";
//Create date object
$date = DateTime::createFromFormat('d.m.Y H:i:s', $raw);
//Print out date object
echo $date->format('Y-m-d h:i:s');
?>
The documentation for createFromFormat can be found here: http://php.net/manual/en/datetime.createfromformat.php
Conor.
Solved this by removing the decimal but also spotted a misuse of the object.
Related
I am on point where I have to usk on forum.
So, I have an array that is my return from join table sql query.
i am displaying it correctly without the problem.
but some of those values I want to put in different table of mysql database.
$array = joint_table();
$array_value = array['key'];
I can echo array_value and it's displaying correctly, also checked variable type and it returns STRING.
however when I am inserting it into the table, it's empty cell.
I am inserting other stuff like date() and such and that is inserted correctly.
So my sql query works fine, besides I am using same query in other places without problem.
Only values I have from that array are not inserting, but still can echo them.
<?php
$page_title = 'Complete Task';
require_once('includes/load.php');
// Checkin What level user has permission to view this page
page_require_level(2);
$task = join_task_table((int)$_GET['id']);
?>
<?php
if(isset($_POST['complete_task'])){
$area = $task['area'] ;
$jig = $task['jig'];
$desc = $task['description'];
$freq = $task['freq'];
$date = make_date();
$user = current_user();
$user_done = remove_junk(ucfirst($user['name']));
$comment = remove_junk($db->escape($_POST['comment']));
if(empty($errors)){
$sql = "INSERT INTO tpm_history (area_name,jig_name,description,frequency,date_done,done_by_user,comment)";
$sql .= " VALUES ('{$area}','{$jig}','{$desc}','{$freq}','{$date}','{$user_done}','{$comment}')";
$result = $db->query($sql);
if($result && $db->affected_rows() === 1){
$session->msg('s',"Job Completed");
redirect('home.php', false);
} else {
$session->msg('d',' Sorry failed to complete the task!');
redirect('task_complete.php?id='.$task['id'], false);
}
} else{
$session->msg("d", $errors);
redirect('task_complete.php?id='.$task['id'],false);
}
}
?>
I am lost. Help.
I'm trying to update multiple cells in a MySQL database based on a previous update date. I am having an issue with unchanged, trailing cells updating to 0.
Database table looks like this (default = 0 for Day#; N = last update date):
id--Run--Day1--Day2--Day3--Day4
1----N------1-----2-----3----4
The code below does the following:
Retrieves the database entry under column= Run, id=1
Subtracts that date from today's date.
Uses that difference to move database for Day1->Day4 to the left.
Example database table when the difference is 2 days:
id--Run--Day1--Day2--Day3--Day4
1----N------3-----4-----3----4
My issue is that I need it to change all trailing Days to 0. So in this example, Day3 & Day4 should both be 0.
I've been trying out another foreach() statement within but can't get the logic behind it. Would someone please point me in the right direction?
$DaysColumnRange2 = range (1, 4);
foreach ($DaysColumnRange2 as $DaysColumnRangeLoop2){
$SubtractedDaysColumns2 = $DaysColumnRangeLoop2 - $diff2format;
$MoveToNewDay2 = ${$Day.$SubtractedDaysColumns2};
$OriginalOldDay = $diff2format + $SubtractedDaysColumns2;
$sql2 = "UPDATE users SET Day$MoveToNewDay2='$OriginalOldDay' WHERE id='$id'";
if ($conn->query($sql2) === TRUE) {
echo "RECORDS UPDATED SUCCESFULLY";
} else {
echo "Error updating record: " . $conn->error;
}
}
I'll update this first post with my attempts as I continue to work on it.
(this is not a great way of doing it, but this is what I was able to put together since Cron jobs wasn't reliable & I haven't yet figured out how MySQL Triggers work)
**
------------------UPDATE--------------
**
This section is to clarify my question.
Let's say this is my database right now:
id--Run--Day1--Day2--Day3--Day4
1----N------1-----2-----3----4
I run the code below where $diff2format = 2:
//>Database credentials + login here
//Retrieve database entry for Run
$id = 1;
$todaysdateupdate = date("Y-m-d");
$lastupdatequeryresult = mysql_query("SELECT Run FROM users WHERE id='$id'");
$lastupdaterow = mysql_fetch_assoc($lastupdatequeryresult);
//Compare Run date to today's date.
$date3=date_create($lastupdaterow['Run']);
$date4 = date_create(date("Y-m-d"));
$diff2=date_diff($date3,$date4);
$diff2format = $diff2->format("%a");
//Day1, 2, 3, etc...
$result1 = mysql_query("SELECT Day1 FROM users WHERE id='$id'");
$row1 = mysql_fetch_assoc($result1);
//Hard coded "Day#" variables
$Day = "Day";
$Day1 = $row1['Day1'];
$Day2 = $row2['Day2'];
$Day3 = $row3['Day3'];
$Day4 = $row4['Day4']; //etc
//MY QUESTION STARTS HERE****************
$DaysColumnRange2 = range (1, 4);
foreach ($DaysColumnRange2 as $DaysColumnRangeLoop2){
$SubtractedDaysColumns2 = $DaysColumnRangeLoop2 - $diff2format;
$MoveToNewDay2 = ${$Day.$SubtractedDaysColumns2};
$OriginalOldDay = $diff2format + $SubtractedDaysColumns2;
$sql2 = "UPDATE users SET Day$MoveToNewDay2='$OriginalOldDay' WHERE id='$id'";
if ($conn->query($sql2) === TRUE) {
echo "RECORDS UPDATED SUCCESFULLY";
} else {
echo "Error updating record: " . $conn->error;
}
}
The output for the database is below. Basically it copied Day3 moved it 2 times to the left, then copied Day4 and also moved 2 times to the left. Nothing changed with Day3 or Day4.
id--Run--Day1--Day2--Day3--Day4
1----N------3-----4-----3----4
But I need it to output this instead:
id--Run--Day1--Day2--Day3--Day4
1----N------3-----4-----0----0
first, i am pretty new to PHP and MySQL, so i still code precedurally.
I am working on an application that takes transactions and pays out a due amount at a certain maturity date to users who have previously made a donation. i have a function knapSolveFast2 that solves the knapsack problem (where a set of transaction amounts in a database adds up to a due amount for a users who's maturity date is up). currently, my demo database looks like this:
if my current date (now) = 2017-04-03 11:36:03 = CAST(NOW() AS DATETIME), my application is meant to loop through the database, fetch users whose maturity_date is >= 1 month from tran_date (i.e. WHERE maturity_date <= CAST(NOW() AS DATETIME) ). Take each user found and pair them for payment in a while loop to other users tran_amt in the database whose tran_amt sums up to the maturity users found due_amount using the knapsack function knapSolveFast2.
Question:
after finding the user with maturity date due for payment (2 users) with the first while loop, i am trying to run an inner while loop to pair each user to other users whose tran_amt sums up to the fetched user's due amount. the problem here is, the inner while loop only runs for the first user found an not for thesecond user.
The code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$connect = #mysqli_connect($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
die("<pre><h1>Sorry, we are experiencing a little Downtime!</h1></pre>");
}
//include the match controller containing the knapSolveFast2 function
include('controller/match.php');
//UPDATE `pendingpair`SET `maturity_date`= DATE_ADD(`tran_date`, INTERVAL 1 MONTH)
//select user to be paid
$sql = "SELECT `user_id`, `due_payment` FROM `pendingpair` where `maturity_date` <= CAST(NOW() AS DATETIME) ORDER BY `id` ASC";
$queryRun = mysqli_query($connect, $sql);
$num_rows = mysqli_num_rows($queryRun);
if ($num_rows > 0) {
while ($row = mysqli_fetch_assoc($queryRun)) {
$user_id_due = $row['user_id'];
$user_amt_due = $row['due_payment'];
print_r($row);
/* Perform queries to select users to pay $user_id_due the sum of $user_amt_due; Where:
- user to be paid, $user_id_due, is not included in the pairing logic
- transacton payment to be chosen, ph_conf = 1, has been confirmed
- transaction has not yet been paired for payment, tran_paired_status = 0
- transactions have not been flaged for fake POP (proof of Payment), `ph_denied_fpop`= 0
*/
$fetchQuery = "SELECT `tran_inv`, `tran_amt`, `user_id` FROM `pendingpair`WHERE `tran_amt` <= {$user_amt_due} && `user_id` != {$user_id_due} && `ph_conf`=1 && `tran_paired_status` = 0 && `ph_denied_fpop`=0 ORDER BY `id`";
$m = array(); // Match Memo items array
$picked_trans = array();
$numcalls = 0; // number of calls made to get Match
$tran_inv = array();
$tran_amt = array();
$user_id = array();
//run query and throw users that fit the criteria into an array
if ($queryRun = mysqli_query($connect, $fetchQuery)) {
//check if data was pulled
if (mysqli_num_rows($queryRun) != NULL) {
//grab data from array and insert it into an array
while ($row = mysqli_fetch_assoc($queryRun)) {
//Populate Arrays to be used
$tran_amt[] = $row['tran_amt'];
$tran_inv[] = $row['tran_inv'];
$user_id[] = $row['user_id'];
}
}
}
## Solve
list ($m4,$pickedItems) = knapSolveFast2($tran_amt, $tran_amt, sizeof($tran_amt) -1, $user_amt_due, $m);
# Display Result
echo "<b><br><br>Invoice:</b><br>".join(", ",$tran_inv)."<br>";
echo "<b>Tran Amt:</b><br>".join(", ",$tran_amt)."<br>";
echo "<b>User_id:</b><br>".join(", ",$user_id)."<br>";
echo "<b>Max Value Found:</b><br>$m4 (in $numcalls calls)<br>";
}
}
?>
the result of the first while loop that finds user with the proper maturity date criteria is:
Array
(
[user_id] => 9
[due_payment] => 150
)
Array
(
[user_id] => 2
[due_payment] => 150
)
this means 2 users are due. but on trying to loop these users. the match for the second user is never found... only that of the first user is.
Array
(
[user_id] => 9
[due_payment] => 150
)
Invoice:
1102, 9022, 9113, 9029, 9116
Tran Amt:
100, 50, 100, 50, 50
User_id:
2, 5, 8, 5, 7
Max Value Found:
150 (in 19 calls)
Please help me figure out what i am missing. Thaaaaank you :)
Your problem is that you call the variables the same thing.
If you look at :
while ($row = mysqli_fetch_assoc($queryRun)) //External loop
Inside that loop you have another
while ($row = mysqli_fetch_assoc($queryRun)) //Internal loop
So the variables inside the external loop, you are using for the internal loop are essentially overwriting the External loops variables, and thus when it is time for the second run of your External loop, the code think it is done, since it is refering to the internal loops variable
To fix this, you must rename the variables you use for the internal loop
Note SECOND_ for both the queryRun and the row
Try this:
if ($SECOND_queryRun = mysqli_query($connect, $fetchQuery)) {
//check if data was pulled
if (mysqli_num_rows($SECOND_queryRun) != NULL) {
//grab data from array and insert it into an array
while ($SECOND_row = mysqli_fetch_assoc($SECOND_queryRun)) {
//Populate Arrays to be used
$tran_amt[] = $SECOND_row['tran_amt'];
$tran_inv[] = $SECOND_row['tran_inv'];
$user_id[] = $SECOND_row['user_id'];
}
}
}
I'm looking at an odd issue with Internet Explorer 9. The below code successfully generates a populated CSV file when ran in Safari, IE8, IE10, IE11, Chrome and Firefox but generates an empty CSV file (Headers only) in IE9. It does not appear to be a data issue considering the bug only appears to happen in IE9. I've been able to test and confirm on 3 different machines running IE9.
It's a legacy script I inherited with SQLSRV instead of MSSQL PDO, though I took the liberty of scooping out mysql and replacing it with PDO and wrapping it in a function and thoroughly commenting it for my own sanity.
# Create a CSV sheet with details we need
# Generate file name based on timestamp
$file = "$_SESSION[user_name]_" . "tutorincomplete_" . date("Y-m-d_H-i-sa");
# 1: Open CSV File
$myFile = ".\csv\\" . "$file.csv";
$fh = fopen($myFile, 'w') or die("can't open file");
# Get list of active classes from MSSQL DB
$sql = "SELECT DISTINCT
static_title,
LEFT(CONVERT(VARCHAR, course_end_date, 120), 150) AS course_end_date,
RTRIM(static_code) as static_code,
RTRIM(session_code) as session_code,
staff_name
FROM
snip";
# Append to query where a school is present
if (ISSET($_SESSION['user_school']) AND $_SESSION['user_school'] != "None")
{
$sql .= "
WHERE
school = ?
ORDER BY staff_name ASC";
$params1 = array($_SESSION['user_school']);
$query = sqlsrv_query($conn, $sql, $params1);
}
else
{
if (isset($_POST['school']) AND $_POST['school'] != "All") {
$sql .= "
WHERE
school = ?
ORDER BY staff_name ASC";
$params1 = array($_POST['school']);
$query = sqlsrv_query($conn, $sql, $params1);
} else {
$sql .= "
ORDER BY staff_name ASC";
$query = sqlsrv_query($conn, $sql);
}
}
$today = date('U');
# Set headers for CSV file
$head = array("Static title", "Course end date", "Static code", "Session code", "Staff name");
fputcsv($fh, $head);
$count = 0;
# Loop through MSSQL results for comparison
while ($obj = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC))
{
$finish = $obj['course_end_date'];
# Strip the time (keep ISO date format intact)
$finishSub = substr($finish, 0, 10);
# Create timestamp from date format
$finishTs = strtotime($finishSub);
# Compare and display <option> tag if valid
if ($today > ($finishTs - 604800))
{
# Fetch information on course; Decide of course is complete or incomplete
# To do this, first check for course entries in the MySQL database
# If they are present, we will use MySQL instead of MSSQL (To reference completed courses)
$sql3 = "SELECT * FROM snip WHERE static = :stc AND session = :sec ORDER BY static ASC";
$query3 = $pdo->prepare($sql3);
$query3->bindParam(':stc', $obj['static_code']);
$query3->bindParam(':sec', $obj['session_code']);
$query3->execute();
$rowCount = $query3->rowCount();
# Check for result count in MySQL
if ($rowCount > 0)
{
$result = $query3->fetch(PDO::FETCH_OBJ);
if ($result->complete == 0) {
$incomplete = 1;
} else {
$incomplete = 0;
$count++;
}
} else {
# No MySQL entry; Mark as incomplete
$incomplete = 1;
}
if ($incomplete > 0)
{
$arr = array($obj['static_title'], $obj['course_end_date'], $obj['static_code'], $obj['session_code'], $obj['staff_name']);
fputcsv($fh, $arr);
}
}
}
echo "
<h1>CSV file generation complete</h1>
<p>Skipped $count classes</p>
<p>File generation complete. File name $file.csv Click here to open</p>";
}
In anything but IE9, it generates "Skipped X classes", CSV file has x number of entries.
But in IE9, "Skipped 0 classes", CSV file only contains column headers.
EDIT: I found out through some experimentation that SQLSRV is passing an empty array ONLY in IE9. It's not affecting any other browser. As such I was able to impress upon the powers that be that I need to switch the system to PDO for MSSQL. Guess I can call this fixed but unresolved.
Is it possible to have a image that will change if an sql record is created since the last visit of that registerd user and another image if criteria not met.
The record table is matningar with a date field datum.
Maybe the below code something close to achieving this?!
<?php
$stmt = "SELECT * FROM matningar WHERE `datum` > date("F j, Y, g:i a", $database- >getLastUserRegisteredDate()";
$result=mysql_query($stmt);
foreach($result as $rec){
echo "<img src=\"images/somepicture.png\" />";
}
?>
Would really appreciate some input on how to proceed!
I believe the best approach to this would be to store the updated record time using this method when creating your table.
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
This way when you SELECT records from the database and you're displaying them on the page, you can do something like so to display separate images based on current users last visit:
foreach($results as $record) {
if($record['updated'] > $currentUser->getLastVisited()) {
echo "<img .... />"; // Has been modified since last visit
} else {
echo "<img .... />"; // Not been modified since last visit
}
// Display rest of this record
}
You could count the records returned and use conditional statements to determine what image you want to display. For example using your code:
/* Using a mysql query which is discouraged and will be depreceated in future */
// declare variables
$i = 0;
$lastRegisteredDate = date("F j, Y, g:i a", $database->getLastUserRegisteredDate());
// declare statement string
$stmt = "SELECT * FROM matningar WHERE `datum` > $lastRegisteredDate";
// execute query
$result=mysql_query($stmt);
// make sure query executed properly
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// manually count the number of results
while ($row = mysql_fetch_assoc($result)) {
$i++;
}
// display image based on conditions
if($i == 0) {
// display one image
}
else {
// display another image
}
Just as a side note mysql functions are going to be depreceated in upcoming PHP releases so I would start looking at using the PDO or mysqli libraries for mysql queries.
/* Using the PDO library */
// declare variables
$i = 0;
$lastRegisteredDate = date("F j, Y, g:i a", $database->getLastUserRegisteredDate());
// declare database handler
$DBH = new PDO( "mysql:host=$host;dbname=$dbname", $user, $pass );
// prepare query
$STH = $DBH->prepare( "SELECT * FROM matningar WHERE `datum` > ?" );
// execute query
$STH->execute( array( $lastRegisteredDate ) );
// set fetch mode
$STH->setFetchMode( PDO::FETCH_OBJ );
// manually count the number of results
while ( $row = $STH->fetch() ) {
$i++;
}
// display image based on conditions
if($i == 0) {
// display one image
}
else {
// display another image
}