PHP/MYSQL Update only first row with defined value - php

I want to update my database using constraints
for ($count = 0; $count <= $size; $count++) {
if($dayOfTheWeek[$count] == "Friday" or $dayOfTheWeek[$count] == "Saturday"){
$query = "UPDATE rota SET title='Guest' WHERE date = '$dateMonthYearArr[$count]' AND starttime = '22:00'";
$dayresult = mysql_query($query);}
}
I have multiple users with a $starttime of 22:00, but i only want the first users detail to be updated leaving the rest unchanged. how would i go about doing this?

If you only want one record to be changed you can append this to the end of your statement:
LIMIT 1
For example:
$query = "UPDATE rota SET title='Guest' WHERE date = '$dateMonthYearArr[$count]' AND starttime = '22:00' LIMIT 1";

Related

When I insert data using PHP it insert more than 10 same data in my table?

I'm trying to create a visitor counter, when user visit the page it will record the time and the number of visitor. But when I refresh the page, my database will be like this:
The code that I do is:
if (empty($counter)){
$counter = 1;
$total = 1;
$time = date('Y-m-d H:i:s');
$sql1 = "INSERT INTO humancount(counter, time, totalHumanCount) VALUES ('$counter', '$time', '$total)";
$result1 = mysqli_query($con, $sql1);
}
//date_default_timezone_set('Asia/Kuala_Lumpur');
$date1 = strtotime("now");
$date2 = strtotime("tomorrow");
echo date("Y-m-d H:i:s", $date1);
echo "<br>";
echo date("Y-m-d H:i:s", $date2);
if ($date1 < $date2){
$plusCounter = $counter + 1;
$plusTotal = $total + 1;
$nextTime = date('Y-m-d H:i:s');
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal'";
$result2 = mysqli_query($con, $sql2);
}
I was expecting that it will record the time of the user visit by every row.
This line of code is overwriting every row in the table with the current counter update:
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal'";
you should instead insert a new row for each new visitor.
Also, this will always be true:
if ($date1 < $date2)
so you can remove the if statement.
You can do something like this:
//first fetch the last values from the database
$sql0 = "SELECT counter, totalHumanCount FROM humancount ORDER BY time DESC LIMIT 1";
$result = mysqli_query($con, $sql0);
if(mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$counter = $row['counter'] + 1;
$total = $row['totalHumanCount'] + 1;
} else {
$counter = 1;
$total = 1;
}
//date_default_timezone_set('Asia/Kuala_Lumpur');
$time = date('Y-m-d H:i:s');
$sql1 = "INSERT INTO humancount(counter, time, totalHumanCount) VALUES ('$counter', '$time', '$total)";
$result1 = mysqli_query($con, $sql1);
Use Where condition in UPDATE query. as per your query every time it will update all rows in table 'humancount'. so add UserID column for unique row and then update row for selected user.
$sql2 = "UPDATE humancount SET counter='$plusCounter', time='$nextTime', totalHumanCount='$plusTotal' WHERE userID = ?";

SQL Updates: Updates Multiple rows rather than Single rows

I am writing a code for MySQL to fetch the 1st row with status is "inactive" and make them "active", but whenever I tried to update the column and make it "active" my query updates multiple rows rather than the single row.
date_default_timezone_set('Asia/Kolkata');
$d = time ();
$date = date("Y-m-d", $d);
$customer_id="1470831854";
$member_details="SELECT * FROM login_update WHERE customer_id ='$customer_id' AND status='inactive' ORDER BY id ASC LIMIT 1 ";
$member = mysql_query($member_details);
while($list = mysql_fetch_array($member)){
$status = $list['status'];
$id = (int)$list['id'];
}
$date_update = "UPDATE login_update SET status='active' WHERE id = '$id'";
$enter_date = mysql_query($date_update);
I think your code should be change as follow
while($list = mysql_fetch_array($member)){
$status = $list['status'];
$customerId = (int)$list['customer_id'];
}
$date_update = "UPDATE login_update SET status='active' WHERE id = '$customerId'";
$enter_date = mysql_query($date_update);
becasue if you get $list['id'] it is always return only 1 unique value from the database then update only one record. I assumed id is your primary key.

Select Query in Group of 10

I followed one link here, and modified my code accordingly. What I am trying to do achieve is for example a table name media_ids contains 45 rows(which is dyanamic), I want to divide the no of rows in a group of 10 rows minimum (in my case four groups of 10 rows and 1 group of 5) and execute code of each group per hour.
For example from select record from id 1 to 10 then second hour from 11 to 20 and so on unless fetches the last record and start again from id 1.
I added a tracker, which check whats the current limit and proceed.But its giving me the required result what I am trying to achieve.
<?php
require('inc/dbConnect.php');
$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];
$lastPointer10=$lastPointer+10;
$currentMediaQuery = "select * from media_ids where id > ".$lastPointer." limit ".$lastPointer.",".$lastPointer10."";
$mediaQuery = mysqli_query($con, $currentMediaQuery);
if (mysqli_num_rows($mediaQuery) > 0) {
while ($row = mysqli_fetch_assoc($mediaQuery)) {
// do stuff…
echo $id=$row['id']."<br>";
}
}
else
{echo "0";}
if ($lastPointer + 10 > 40) {
$lastPointer = 1;
} else {
$lastPointer += 10;
}
mysqli_query($con, "update media_tracker set tracker = $lastPointer");
?>
I am assuming you are calling this script every hour via ajax/Js...
In your code if you delete some data from another script you may find your first row id i.e 100 !
require('inc/dbConnect.php');
$limit = 10 ;
$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];
$lastPointerRes = mysqli_fetch_assoc($lastPointerResult);
$lastPointer = empty($lastPointerRes['tracker']) ? 0 : $lastPointerRes['tracker'] ;
$lastPointer10=$lastPointer* $limit;
$currentMediaQuery = "select * from media_ids limit ".$limit." OFFSET ".$lastPointer10."";
$mediaQuery = mysqli_query($con, $currentMediaQuery);
if (mysqli_num_rows($mediaQuery) > 0) {
while ($row = mysqli_fetch_assoc($mediaQuery)) {
// do stuff…
echo $id=$row['id']."<br>";
}
}
else
{echo "0";}
//do a total row count query here and set as value of $total rather than 40
$total =40 ;
$flag = ceil($total/$limit);
if ($lastPointer == $flag) {
$lastPointer = 0;
} else {
$lastPointer ++;
}
mysqli_query($con, "update media_tracker set tracker = $lastPointer");

Predefined counter not updating in select statement

Here's a simplified code similar to what I'm using. In this one, I'm pulling Names from ID's.
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
What I get is the same name, the counter in the select statement stays at 0.
I had to put the definition of the $select statement and the $result inside the loop, it redefines everything every time we enter the while loop, looks like the code below. That doesn't seem practical and optimal to me. What are the best work-around for situations like these? I'm not really familiar with variable scopes in PHP, I haven't found any good documentation on that matter when it comes to sql functions.
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
Here's the code that I've actually written.
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
Your issue doesn't have to do with variable scope. The $select variable is set once as string with the current value of $counter. Your second example works because this value is reset every time.
In your second example however, you're creating a sql statement that gets 1 row (assuming nID is unique), then looping through your result retrieve that one row. You're doing 10 sql calls, but you only need one if you modify your query like so:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
For your actual code, you should be able to get one record per nUserId by using GROUP BY. Try this:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";

How to list by highest date in PHP

Hey guys so I am having some trouble using the following:
for ($i = 0; $i < count($noncompUsername); $i++)
{
$tsql ="SELECT firstname,lastname,email,phone,statuschangedate FROM csvdata WHERE username = :username ORDER BY statuschangedate";
$tgetmeminfo=$DBH->prepare($tsql);
$tgetmeminfo->execute(array(':username' => $noncompUsername[$i]));
while ($trow = $tgetmeminfo->fetch(PDO::FETCH_ASSOC)){
$csvFirst = $trow['firstname'];
$csvLast = $trow['lastname'];
$csvEmail = $trow['email'];
$csvPhone = $trow['phone'];
$csvDate = $trow['statuschangedate'];
$timediff = strtotime($date) - strtotime($csvDate);
$timediff = floor($timediff/86400);
$sql ="SELECT MailingAdrs FROM insuranceverificationdisclaimer WHERE TraineeUsername = :tusername";
$getmeminfo=$DBH->prepare($sql);
$getmeminfo->execute(array(':tusername' => $noncompUsername[$i]));
while ($row = $getmeminfo->fetch(PDO::FETCH_ASSOC)){
$csvAddrs = $row['MailingAdrs'];
$change = 1;
}
if($change != 1)
{
$csvAddrs = "No address";
}
$change = 0;
echo "$timediff, $csvFirst $csvLast, $csvEmail, $csvPhone, $csvAddrs";
}
echo "
<br>
";
}
Now this works but the part I want to point out is the $tsql ="SELECT firstname,lastname,email,phone,statuschangedate FROM csvdata WHERE username = :username ORDER BY statuschangedate"; - now when I do this and get the integer of the statuschangedate to the current date and print it out as an integer, it is not ordered properly based on the date.
So I need to get this to order by the oldest date on top and as follows...
Thank you!
David
Order the date in descending order (using DESC):
... ORDER BY statuschangedate DESC
If you want to order based on $timediff you should change the ORDER clause to this:
ORDER BY DATEDIFF(:date, statuschangedate)
Granted, this should actually give the same ordering you already had, but you could at least use this expression to save some processing in PHP itself :)

Categories