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
}
Related
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.
I am having trouble with changing over some code from old style mysql queries to being prepared. I assume the problem is due to the fact that I'm using multiple whiles which each have their own query in which is causing problems cause only one prepared statement can be active at a time.
EDIT: If anyone cares, I've made it work with only 2 loops like so -
function createDeskMenu()
{
global $bookingTimes, $dbconn;
$day0 = mktime(0, 0, 0, date("m") , date("d"), date("Y"));
$query = "SELECT location FROM location";
$result = mysqli_query($dbconn,$query);
mysqli_num_rows($result);
while ($row = mysqli_fetch_array($result))
{
$location = $row['location'];
echo "<h3>$location</h3><div>";
$query = $dbconn -> prepare("SELECT COALESCE( CountDesk, 0 ) total, name, d.desk_id, phone, fax, dock, pc FROM desk d LEFT JOIN (SELECT COUNT(booked.desk_id) CountDesk, desk_id FROM booked WHERE booking_id >=?)b ON d.desk_id = b.desk_id WHERE location=?");
$query->bind_param("is",$day0, $location);
$query->execute();
$query->bind_result($totalCount,$name,$desk_id,$phone,$fax,$dock,$pc);
while($query->fetch()) {
$total = count($bookingTimes) * 14 - $totalCount;
echo '<a href="?page=desk&desk='.$desk_id.'"><div class="desk"><b>'.$name.'
('.$total.' Available Bookings)</b><li>Facilities:';
if($phone){echo " Phone,";}if($fax){echo " Fax Machine,";}if($dock){echo " Laptop Dock.";}if($pc){echo " Desktop Workstation.";}
echo '</li></div></a><hr />';
}
$query->close();
echo '</div>';
}
}
You cannot prepare() a statement while the connection has rows waiting to be fetched from another statement. You must first either close the previous result set or fetch all rows from it.
However...
I don't see the need for the outer query which retrieves location at all, as it has no WHERE clause. You are selecting all locations, and can therefore omit that part entirely. All you are using the outer loop for is to create a <h3> for each location, and this is extremely wasteful ( in addition to originally causing you breakage in the code)
Instead, do one query and in the fetch loop, check if the location has changed. When it changes, output your header
echo "<h3>$location</h3><div>";
So remove the outer query and loop entirely, and use a pattern like the following to detect changes in location. Make sure to ORDER BY location so they are sorted for you.
No bound parameters are needed. You can do this with a query() call since the location is no longer variable and $day0 is known to be a timestamp from mktime().
// Substitute a query() call and $day0 can be inserted directly.
// This one query fetches all locations sorted...
$query = $dbconn->query("
SELECT
COALESCE( CountDesk, 0 ) total,
name,
d.desk_id,
phone,
fax,
dock,
pc
FROM
desk d
LEFT JOIN (
SELECT COUNT(booked.desk_id) CountDesk, desk_id FROM booked WHERE booking_id >= $day0
)b ON d.desk_id = b.desk_id
ORDER BY location");
// Store the last location in a variable which starts empty...
$location = "";
while($row = $query->fetch_assoc()) {
// on change of $location, update the variable.
if ($location !== $row['location']) {
$location = $row['location'];
// And output the new location value
echo "<h3>$location</h3><div>";
}
// Do the rest of your loop.
$total = count($bookingTimes) * 14 - $row['total'];
echo '<a href="?page=desk&desk='.$row['desk_id'].'"><div class="desk"><b>'.$row['name'].'
('.$total.' Available Bookings)</b><li>Facilities:';
if($row['phone']){
echo " Phone,";
}
if($row['fax']){
echo " Fax Machine,";
}
if($row['dock']){
echo " Laptop Dock.";
}
if($row['pc']){
echo " Desktop Workstation.";
}
echo '</li></div></a><hr />';
}
$row->close();
echo '</div>';
Now on to the reason it was failing.... You cannot prepare() a new statement while there are rows remaining to be fetched from a previous statement or query. You must first either fetch all the rows, or close the statement with $stmt->close(). So effectively you cannot nest fetch loops.
The better method is to first fetch all rows into an array and then loop over that array:
while ($row = $first_query->fetch()) {
// Append all onto an array
$first_query_rows[] = $row;
}
// Then loop over that
foreach ($first_query_rows as $row) {
// Do a new query with $row
}
Usually though, this can be solved with a proper JOIN.
I´m trying to get uses to the PHP PDO Syntax. Maybe somone can have a look at this peace of code. It seems it´s a bit much lines for little effort.
I catch a User Post-Input (ID). Know I need for calculation reason the values BejagFlach from all Users (the sum of them) and the single value BejagFlach from the User identified by the ID. Do I need two querys for this like here? or is there are shorter/better way?
/* Fetch POST Data */
$User_Num = $_POST['User_Num'];
/* Build query for one User */
$dbSelect = $objDb->prepare("SELECT BejagFlach,Name FROM Benutzer WHERE lfdNr = :User_Num");
$dbSelect -> setFetchMode(PDO::FETCH_ASSOC);
$dbSelect->execute(array(':User_Num' => $User_Num));
/* Build query for all Users */
$dbSelect2 = $objDb->prepare("SELECT BejagFlach FROM Benutzer");
$dbSelect2 -> setFetchMode(PDO::FETCH_ASSOC);
$dbSelect2->execute();
/* Output + Calculate */
while($row = $dbSelect->fetch()) {
$totalUser += $row['BejagFlach'];
$who = utf8_encode($row['Name']);
}
/* Output + Calculate */
while($row = $dbSelect2->fetch()) {
$totalAll += $row['BejagFlach'];
}
Kind regards,
toni
Since you need at least your second query, I would do like this so you do only 1request to the database :
$dbSelect = $objDb->prepare("SELECT BejagFlach,lfdNr FROM Benutzer");
$dbSelect -> setFetchMode(PDO::FETCH_ASSOC);
$dbSelect ->execute();
while($row = $dbSelect->fetch()) {
$totalAll += $row['BejagFlach'];
if( $row['lfdNr'] == $UserNom) {
$totalUser += $row['BejagFlach'];
$who = utf8_encode($row['Name']);
}
}
No, it doesn't seem too much?
The only thing I would change, is if you are only after the number of records matched, use rowCount
<?php
$sel = $dbh->prepare('select * FROM fruit');
$sel->execute();
/* Return number of rows that were deleted */
print("Return number of rows that were selected:\n");
$count = $sel->rowCount();
print("Seleted $count rows.\n");
?>
I am creating a pagination script and I need to get the first and last results in the database query so that I can determine what results appear when the user clicks a page to go to. This is the code that I have at the minute:
// my database connection is opened
// this gets all of the entries in the database
$q = mysql_query("SELECT * FROM my_table ORDER BY id ASC");
$count = mysql_num_rows($q);
// this is how many results I want to display
$max = 2;
// this determines how many pages there will be
$pages = round($count/$max,0);
// this is where I think my script goes wrong
// I want to get the last result of the first page
// or the first result of the previous page
// so the query can start where the last query left off
// I've tried a few different things to get this script to work
// but I think that I need to get the first or last result of the previous page
// but I don't know how to.
$get = $_GET['p'];
$pn = $_GET['pn'];
$pq = mysql_query("SELECT * FROM my_table ORDER BY id ASC LIMIT $max OFFSET $get");
// my query results appear
if(!$pn) {
$pn = 1;
}
echo "</table><br />
Page $pn of $pages<br />";
for($p = 1;$p<=$pages;$p++) {
echo "<a href='javascript:void(0);' onclick='nextPage($max, $p);' title='Page $p'>Page $p</a> ";
}
I think you have few problems there, but I try to tackle them for you. First, as comments say above, you are using code that it vulnerable to SQL injection. Take care of that - you might want to use PDO, which is as easy use as MySQL extension, and will save you from many trouble (like injection).
But to your code, lets go through it:
You should ask DB to get count of the rows, not using mysql function, it's far more effective, so use SELECT count(*) FROM mytable.
For $pages use ceil() as you want all rows to be printed, if you have $max 5 and have 11 rows, round will make $pages 2, where you actually want 3 (last page just contains that last 11th row)
in LIMIT you want to LIMIT row_count OFFSET offset. You can calculate offset from page number, so: $max = row_count but $offset = ($max * $page) - $max. In your code if $get is directly the page, it means you get $get'th row (Not sure though what happens in your JS nextpage. Bare in mind that not all use JavaScript.)
I have prepared simple example here which uses PDO, maybe that gives you idea how simple it's use PDO.
The selecting rows shows example how to put parameters in SQL, it would be perfectly safe in this case state, 'SELECT * FROM pseudorows LIMIT '.$start.','.$max by I wanted to make an example how easy it is (and then safe):
// DB config
$DB_NAME = 'test';
$DB_USER = 'test';
$DB_PASSWD = 'test';
// make connection
try {
$DB_CONN = new PDO("mysql:host=localhost;dbname=".$DB_NAME, $DB_USER, $DB_PASSWD);
$DB_CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die($e);
}
// lets say user param 'p' is page, we cast it int, just to be safe
$page = (int) (isset($_GET['p'])?$_GET['p']:1);
// max rows in page
$max = 20;
// first select count of all rows in the table
$stmt = $DB_CONN->prepare('SELECT count(*) FROM pseudorows');
$stmt->execute();
if($value = $stmt->fetch()) {
// now we know how many pages we must print in pagination
// it's $value/$max = pages
$pages = ceil($value[0]/$max);
// now let's print this page results, we are on $page page
// we start from position max_rows_in_page * page_we_are_in - max_rows_in_page
// (as first page is 1 not 0, and rows in DB start from 0 when LIMITing)
$start = ($page * $max) - $max;
$stmt = $DB_CONN->prepare('SELECT * FROM pseudorows LIMIT :start,:max');
$stmt->bindParam(':start',$start,PDO::PARAM_INT);
$stmt->bindParam(':max', $max,PDO::PARAM_INT);
$stmt->execute();
// simply just print rows
echo '<table>';
while($row = $stmt->fetch()) {
echo '<tr><td>#'.$row['id'].'</td><td>'.$row['title'].'</td></tr>';
}
echo '</table>';
// let's show pagination
for($i=1;$i<=$pages;$i++) {
echo '[ '.$i.' ]';
}
}
mysql_fetch_array returns an associative array
Which means you can use reset and end to get the first and last results:
$pqa = mysql_fetch_array($pq);
$first = reset($pqa);
$last = end($pqa);
I don't see how you plan to use the actual results, just page numbers should be sufficient for pagination.
Still, hope it helps. And yes, upgrade to mysqli, so your code doesn't get obsolete.
I tried to search for something similar in the web but no results.
What I am trying to do is simply taking the results from the DATABASE and then run some functions for EACH result.
We have two kinds of functions.
The first function is when the row "Type" is = F , the second one when the row "Type" is = T.
The problem that I am having with this code is that it runs the functions ONLY for the first mySQL result.
But I have more results in the same time, and the functions should run for EACH mySQL result and not only for the first one.
I do not know if I need a foreach or whatever. I do not know anything about arrays and php loops.
Thank you.
include_once("../dbconnection.php");
date_default_timezone_set('UTC');
$TimeZone ="UTC";
$todaydate = date('Y-m-d') ."\n";
$time_utc=mktime(date('G'),date('i'),date('s'));
$NowisTime=date('G:i:s',$time_utc);
$MembID =(int)$_COOKIE['Loggedin'];
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$queryMAIN="SELECT * FROM TableTuit WHERE TimeZone ='".$TimeZone."' AND Date ='".$todaydate."' ORDER BY ID ASC";
$result=mysql_query($queryMAIN) or die("Errore select TableT: ".mysql_error());
$tot=mysql_num_rows($result);
while($ris=mysql_fetch_array($result)){
$text=$ris['Tuitting'];
$account=$ris['IDAccount'];
$memberID=$ris['memberID'];
$type=$ris['Type'];
$id=$ris['ID'];
$time=$ris['Time'];
if($time <= $NowisTime){
if($type=="F") //if the row type is = F, then do the things below
{
$queryF ="SELECT * FROM `TableF` WHERE `memberID`='$MembID' AND `ID`='$account'";
$result=mysql_query($queryF) or die("Errore select f: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0) {
$row = mysql_fetch_assoc($result);
DO FUNCTION // Should call the function that requires the above selected values from $queryF. Should Run this function for every mysql result given by $queryMAIN where row "type" is = F
}
}
}
if($type=="T") //if the row type is = T, then do the things below
{
$queryT = $queryF ="SELECT * FROM `TableT` WHERE `memberID`='$MembID' AND `ID`='$account'";
$result=mysql_query($queryT) or die("Errore select $queryT: ".mysql_error());
$count = mysql_num_rows($result);
if ($count == 0)
$Isvalid = false;
else
{
$Isvalid = true;
$row = mysql_fetch_assoc($result);
}
if($Isvalid){
DO THIS FUNCTION // Should call the function that requires the above selected values from $queryT. Should Run this function for every mysql result given by $queryMAIN where row "type" is = T
}
}
}
}//END OF MYSQL WHILE OF $queryMAIN
You are using $result for the outer Query ($result=mysql_query($queryMAIN); and the Query inside the while loop $result=mysql_query($queryF); - I believe you do not want to mix these?
Right now you process the first row from TableTuit, then overwrite the $result with a row from TableF or TableT. In the next loop, the following columns will not be found in the array (unless they are also in these two tables, of course):
$text=$ris['Tuitting'];
$account=$ris['IDAccount'];
$memberID=$ris['memberID'];
$type=$ris['Type'];
$id=$ris['ID'];
$time=$ris['Time'];
You are loading the results into an array, try using this in your while loop instead:
while($ris=mysql_fetch_assoc($result)){