How to update MySQL table by calculated form value? - php

I'm trying to update MySQL table recored by any calculated form values in php, but it doesn't work. May you help me please thank you.

You should use mysqli with prepared statements, like so.
I hope this is enough for you, you gave me nothing to work with so...
<?php
//Get the form value and ID of the database record to update
$value = $_POST['value']; // Value submitted by a form element (replace this with whatever you want to change)
$id = $_POST['id']; //ID, could be of the user etc. (this will be a primary key inside the database) (does not have to be submitted via POST, I assume you know this already)
//Establish a new mysql connection
$mysqli = new mysqli($db_host,$db_user,$db_pass,$db_name);
//Set up a query
$query = "UPDATE table SET column_one=? WHERE id=?";
//Prepare the statement
$stmt = $mysqli->prepare($query);
//Bind the parameters
// 'si' = in the order of submitted valurs (column_one=? and id=?) (column_one is s and id is i, s is for string, i is for integer) (this defines what types of variables we are sending)
$stmt->bind_param('si', $value, $id);
//Execute the query
if($stmt->execute()){
//Get the amount of affected rows
$affected = $stmt->affected_rows(); //Should only be 1, but if your ID or whatever you're using to define which parts of the DB to update is not unique, then it can go higher ofc.
//Show success
echo "Database updated, $affected rows affected";
}else{
//Show error
echo "Error, say that this is shown, on stack overflow, as there's obviously something wrong.";
}
//Close the stmt/mysqli stuff
$stmt->close();
$mysqli->close();

Related

how to use 2 inserts in the same record PHP SQL

I am using the below code to grab a users ID from another table and creating a new record in this table. in the same row there is a field called action and I would like to insert either 'Log-In' or 'Log-Out' in this field for the same record.
my question is im not sure how to incorporate it with the code below without the database creating a new blank line
try{
// check for user ID in sessions table and apply to new session_log record
$sql = "INSERT INTO session_logs (USER_ID, first, last, email) SELECT USER_ID, first, last, email FROM sessions WHERE email=:email";
$stmt = $pdo->prepare($sql);
// Bind parameters to statement
$stmt->bindParam(':email', $_REQUEST['email']);
// Execute the prepared statement
$stmt->execute();
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
Unfortunately, Table and Column names CANNOT be replaced by parameters in PDO so you cant just bind the SELECT column as a value or similar, however, you can manipulate the string yourself to add in the required value like so:
$action = 'Log-In'; // if you get this value from user input in any way, be sure to sanitize it with something like `mysqli_real_escape_string`
$sql = "INSERT INTO session_logs (USER_ID, first, last, email, action) SELECT USER_ID, first, last, email, '$action' FROM sessions WHERE email=:email";

Insert data into a column if no data in column

How do I insert data into a column if that column has no values? This piece of code will not insert any values, unless I take out the if statement. Of course that isn't what I want, since that means each time the code is run, more data will be inserted into the column 'datagroup'.
include('dg_config.php');
# select column datagroup from table data
$stmt = $db -> prepare("SELECT datagroup FROM data");
$stmt->execute();
# fetch rows from data
while($row = $stmt->fetch()){
if (empty($row['datagroup'])){
$insertdg = "INSERT INTO data (datagroup)
VALUES ('Data Definitions'),('Policies'),('Systems and Process Documents'),('Purchase Orders'),('Invoices')";
$db ->exec($insertdg);
}
}
P.S dg_config.php contains the variable $db which is used for MySQL connection. Also, I have no values in the column so UPDATE won't work.
Desired output:
If you want to check if there are no records first and only insert the values then, a quick way from where you are is to say if the fetch() fails to retrieve a row then do the insert...
include('dg_config.php');
# select column datagroup from table data
$stmt = $db -> prepare("SELECT datagroup FROM data");
$stmt->execute();
if ( !$stmt->fetch() ){
$insertdg = "INSERT INTO data (datagroup)
VALUES ('Data Definitions'),('Policies'),('Systems and Process Documents'),('Purchase Orders'),('Invoices')";
$db ->exec($insertdg);
}
// re fetch the data
$stmt->execute();
This removes the while() loop altogether.

PHP - Get variable from database based on another variable

I am using PHP to do some database projects for school in a self pace class, so I don't know much of the syntax. I am trying to change a row of by database based on the ID given.
Heres some pseudocode of what I want to accomplish:
if(databaseRowWithThis$id name == x)
UPDATE database SET name = '$name' WHERE id='$id';
If this is confusing, please tell me and I'll try to clear it up.
Thanks in advance.
PHP with Syntax
$conn = mysqli_connect($server,$login,$pw,$database); // connection info
$sql = "UPDATE yourtablename SET name= ? WHERE id=?"; // placeholders for parameters
$stmt = $conn->prepare($sql); // prepare the query
if($stmt){
$stmt->bind_param("is",$id,$name); // bind the parameters to the ?, i for integers, s for string, must be in exact order as the query
$stmt->execute(); // execute
$stmt->close(); // close statement
}
$conn->close(); // close the connection

Getting last inserted row in access using php

I'm inserting into an Access database via PHP but I'm struggling to get the ID of the last inserted row. I have had this working previously but our server broke and I've had to re-write it, but it doesn't return - I'm sure this is how I did it:
$idquery = "select ##IDENTITY from [Businesses]";
try{
$rs = $conn->execute($query);
$idReturned = $conn->execute($idquery);
echo json_encode($idReturned);
} catch(com_exception $e){
echo($e);
}
The insert is successful but the json_encode($idReturned); is blank, any idea why?
Are you using PDO?
If you are, you can do the following:
$id = $con->lastInsertId();
<?php
// Assume $dbh connection handle is already established
$sql = "INSERT INTO business (name) VALUES ('BUS')";
$sth = $dbh->prepare($sql);
$sth->execute();
$lastId = $dbh->lastInsertId(); //This is where you get last inserted ID
?>
Depends on the DB provider, there might be a situation that you need to set the "Primary key" for that table

update mysqli query with set values

I can update my columns dynamically, but I dont know how to update it with set values (stupid I know)
This is my sql code that updates the columns with set values:
if (isset($_POST['delete'])) {
$sql = 'UPDATE users SET user_deletion_date = NOW(), user_deleted_by = '.$_SESSION['id'].', deleted = Y
WHERE user_id = ?';
if ($stmt->prepare($sql)) {
// bind the query parameters
$stmt->bind_param('i', $_GET['user_id']);
// bind the result to variables
$stmt->bind_result($user_id, $user_deletion_date, $user_deleted_by, $deleted);
// execute the query, and fetch the result
$done = $stmt->execute();
$stmt->fetch();
}
}
if ($done) {
header('Location: update_users_confirm.php');
exit;
}
this doesn't update the table at all, I know that the issue is with my bind_param, could someone please help
Michael B's answer is mostly likely the solution. Change the $_GET to $_POST

Categories