I am working on a project that takes students attendance in class and I want to update the database data through PHP whilst running a SQL function of UPDATE, but I want to be able to update it base on the id of the data.
This is the code that I am working with at the moment.
<?php
require_once './dba.php';
$status = "";
if(isset($_POST['time_in'])) {
$query = "INSERT INTO nameOfTable (datetime) VALUES (NOW())";
$d = $conn->prepare($query);
$d->execute();
} elseif(isset($_POST['time_out'])) {
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = ? ";
$d = $conn->prepare($query);
$d->execute();
} else {
$status = "Can't time in!";
}
Use $conn->lastInsertId() to get the ID that was assigned when they clocked in. Save that in a session variable and use it when they clock out.
<?php
require_once './dba.php';
$status = "";
if(isset($_POST['time_in'])) {
$query = "INSERT INTO nameOfTable (datetime) VALUES (NOW())";
$d = $conn->prepare($query);
$d->execute();
$_SESSION['clock_id'] = $conn->lastInsertId();
} elseif(isset($_POST['time_out'])) {
if (!isset($_SESSION['clock_id'])) {
$status = "You need to clock in first!";
} else {
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
$d->execute(['id' => $_SESSION['clock_id']]);
}
} else {
$status = "Can't time in!";
}
You must remember to prepare the query and bind the parameters onto it.
Use the $id variable to prepare the query with the appropriate ID.
Make sure you authenticate the session before passing the ID to the query, otherwise an attacker can manipulate this data to pull anyone's data they wish.
// Its helpful to create elements within the code to bind onto. :id is ours.
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
// Run the query & bind id to :id
$d->execute(['id' => $id]);
You try update
$query = "UPDATE nameOfTable SET datetime = NOW() WHERE id = :id ";
$d = $conn->prepare($query);
$d->execute(['id' => $id ]);
Related
<?php
$date = date("Y-m-d"); //Return current date in yyyy-mm-dd format
$userIP = $_SERVER['REMOTE_ADDR'];// Stores remote user ip address
$query = "SELECT * FROM `unique_visitors` WHERE `date` = '$date'";
$result = mysqli_query($connection,$query);
if($result->num_rows == 0)// this block will execute when there is no record of current date in database
{
$insertQuery = "INSERT INTO `unique_visitors` (`date`,`ip`) VALUES ('$date','$userIP')";
mysqli_query($connection,$insertQuery);
}
else
{
$row = $result->fetch_assoc();//Extracts result row from result object
if(!preg_match('/'.$userIP.'/i',$row['ip']))//Will execute When Current ip is not in databse
{
$newIP = "$row[ip] $userIP"; //Combine previous and current user ip address with a separator for updating in database
$updateQuery = "UPDATE `unique_visitors` SET `ip`='$newIP', `views`=`views`+1 WHERE `date` = '$date' ";
mysqli_query($connection,$updateQuery);
}
}
?>
Is there a better way to count unique visitors in my website or this simple code is fine to insert into my website?
Here is the basic PHP/mysqli code for the approach you taken. You have to create an unique index for two fields, date and ip. And everything would work with just a single query.
<?php
$userIP = $_SERVER['REMOTE_ADDR'];// Stores remote user ip address
$sql = "INSERT INTO unique_visitors (date, ip, views) VALUES (curdate(),?,1)
ON DUPLICATE KEY UPDATE views = views + 1";
$stmt = $connection->prepare($sql);
$stmt->bind_param("s", $userIP);
$stmt->execute();
$sql = "SELECT count(*) FROM unique_visitors WHERE date = curdate()";
$result = $connection->query($sql);
$visitors = $result->fetch_row()[0];
I was hoping someone would guide me in the right direction. What I am trying to accomplish is the following:
user uploads a csv file the data is then stored in a multidimensional array $formatted_payments. Then I check the records on the file against the records on the DB. I need to check if the route from the file matches the route on DB if it does for all records then commit all the updates but if there is one mismatch then i need to rollback all the update. I hope this all makes sense. Here is what I did but I haven't tested yet.
Thank you
$conn->autocommit(FALSE);
$route_errors = [];
foreach($formatted_payments as $val){
$sql = "SELECT id, account_no, payment_amount, route_id, payment_date FROM car_payments WHERE payment_date = '".$date."' AND account_no = '".$val['account_no']. "'";
$res = $conn->query($sql);
$data = $res->fetch_object();
if($data){
if($val['amount'] > 0){
if($val['route_id'] != $data->route_id){
$route_errors[] = $val['account_no'];
}else{
$sql = "UPDATE car_payments SET payment_amount = ? charged = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sss", $val['amount'], 'Si', $data->id);
$stmt->execute();
}
}else{
$sql = "UPDATE car_payments SET payment_amount = ? charged = ?, pending = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssss", $val['amount'], 'No', 1, $data->id);
$stmt->execute();
}
}
}
if(!empty($route_errors)){
$conn->roll_back();
echo 'The following accounts do not match the route. Records not imported.<br>';
foreach($route_errors as $value){
echo '<li>' . $value . '</li>';
}
}else{
$conn->commit();
}
I have sql + php query and i need inform user when update fail exmpl:
$sql = "UPDATE db SET
date = GetDate(),
...
...
...
WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2'
";
sqlsrv_query( $con, $sql);
And now if php variables values not 100% match values in db update fails but users cant see that. He can check records and try again. I would like inform him when query update nothing.
Like GOB commented, you can use the PHP sqlsrv_rows_affected function to retrieve the number of affected rows. For example:
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
$row_count = sqlsrv_rows_affected( $stmt );
if ($row_count === false)
echo "Error in retrieving row count.";
else
echo $row_count;
Before directly executing update query,check whether condition in update query exists or not. This can be done by selecting count of that condition.
Try below code:
$sql = "select count(*) as count from db WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2' ";
while($row = mysqli_fetch_array($sql))
{
$count = $row['count'];
}
if($count == 0)
{
echo 'update will fail';
}
else
{
$sql = "UPDATE db SET
date = GetDate(),
...
...
...
WHERE name = '$name1' and code = '$code' and value1 = '$value1' and value2='$value2'
";
}
I'm trying to edit data(stored in DB). This is display.php. First it displays data from DB (if no data then blank fields). Then edit button to edit DB.
<html>
<body>
<?php
if(!isset($_POST['edit_pro']))
{
?>
//get data from DB and display in table.
<form>
<input type="submit" name= "edit" value="edit">
</form>
<?php
}
else
{
?>
<form name="edit_DB" action="edit.php">
//edit ...2 <select> fields and 1 text field.
//submit button
</form>
<?php
}
?>
And in edit.php
i simply update the DB. But what if i want to change only 1 field.(problem is all fields gets updated).Here's edit.php
<?php
include_once 'db_connect.php';
$db_con = dbConnect("dbname");
$uid = $_SESSION['uid'];
if(isset($_POST['edit']))
{
$c = $_POST['c'];
$s = $_POST['list'];
$t = $_POST['nm'];
$a = $_POST['a'];
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c,$s,$t,$uid));
header("Location:display.php");
}
?>
$sql = "UPDATE `user` SET `c` = ?, `s` = ?, `t` = ? WHERE u_id = ?";
this query means:
update table user
for each row in this table where u_id = [some value]
set fields C and S and T to some other distinct values
so, your query updates 3 fields at one time, and it is ok, as it what it should do
if you want to change this logic, to update only some fields you need to change query and arguments, for example if you want to change only c use:
$sql = "UPDATE `user` SET `c` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute(array($c, $uid)); // this array binds values to question marks, so count should be the same, we have 2 ? - we must use 2 variables
for c AND t:
$sql = "UPDATE `user` SET `c` = ?, `t` = ? WHERE u_id = ?";
$q = $db_con->prepare($sql);
$q->execute();
if you don't know exactly how many arguments will be, you need dynamic query building, like:
$arr = array();
$sqlA = array();
if (isset($_POST['c']) && $_POST['c']) {
$arr[] = $_POST['c'];
$sqlA[] = '`c`=?';
}
if (isset($_POST['s']) && $_POST['s']) {
$arr[] = $_POST['s'];
$sqlA[] = '`s`=?';
}
if (isset($_POST['t']) && $_POST['t']) {
$arr[] = $_POST['t'];
$sqlA[] = '`t`=?';
}
if (count($arr)) {
$sql = 'UPDATE `user` SET '.implode($sqlA, ',').' where u_id = ?';
$arr[] = $uid;
$q = $db_con->prepare($sql);
$q->execute($arr);
}
That means that WHERE clause of the request doesn't work. Check if you passing a quotation marks " in you variable $t so you close $sql before WHERE clause
The function is supposed to update the values in the database.
Here is the code:
//Functions
//Function to Update users networth
function update_net($name)
{
//Get worth & balance at the time
$sql_to_get_worth_balance = "SELECT * FROM user WHERE username = '$name'";
$sql_query = mysql_query($sql_to_get_worth_balance);
while ($rows = mysql_fetch_assoc($sql_query))
{
$worth = $rows['worth'];
$balance_ = $rows['cash_balance'];
}
//Get net_worth now
$new_net_worth = $worth + $balance;
//Update net_worth
$sql_for_new_worth = "UPDATE user SET net_worth = '$new_net_worth'";
$sql_worth_query = mysql_query($sql_worth);
}
It is used here:
//Get username
$username = $_SESSION['username'];
if (isset($username))
{
//Update networth
$update_worth = update_net($username);
You probably want a WHERE clause on the end of this query:-
$sql_for_new_worth = "UPDATE user SET net_worth = '$new_net_worth'";
e.g.
$sql_for_new_worth = "UPDATE user SET net_worth = '$new_net_worth' WHERE username = '$name';
You're forgetting the where name=$name part in the update query (which will update the entire table!)
I hope your $name can never hold user entered data because your sql is vulnarable to injection.
Maybe:
//Update net_worth
$sql_for_new_worth = "UPDATE user SET net_worth = '$new_net_worth'";
$sql_worth_query = mysql_query($sql_worth);
Should Read:
//Update net_worth
$sql_for_new_worth = "UPDATE user SET net_worth = '$new_net_worth'";
$sql_worth_query = mysql_query($sql_for_new_worth);
May be you should commit transaction?