PHP Prepared Statements, how to shift data from one column to another - php

I'm trying to move the data from one column in my table, to another, and then setting the initial column back to zero. While the initial column is reset back to zero, it also adds that zero onto the end of target column (I'll provide some screenshots for context).
Here is my code:
function complete_da($da_id) {
include 'connect.php';
include 'globals.php';
retrieve_user_data($_SESSION['logged_in']);
nation_data_grab($_SESSION['logged_in']);
echo "u_n_i: ".$user_nation_information['active_da']." <br>";
$ret_da_info_sql = "SELECT `active_da`, `completed_da` FROM `nations` WHERE `nations`.`user_id` = ?;";
$ret_da_info_stmt = mysqli_stmt_init($connect);
if(!mysqli_stmt_prepare($ret_da_info_stmt, $ret_da_info_sql)) {
echo "Statement 1 Failed";
} else {
mysqli_stmt_bind_param($ret_da_info_stmt, "i", $user_data['id']);
mysqli_stmt_execute($ret_da_info_stmt);
// Use get_result for *, bind_result for specific columns
mysqli_stmt_bind_result($ret_da_info_stmt, $active_da, $completed_da);
mysqli_stmt_fetch($ret_da_info_stmt);
echo "u_n_i: ".$user_nation_information['active_da']." <br>";
$updated_cda_str = ($completed_da .= ",".$active_da);
}
mysqli_stmt_close($ret_da_info_stmt);
$update_compl_with_active_sql = "UPDATE `nations` SET `completed_da` = ? WHERE `nations`.`user_id` = ?;";
$update_compl_with_active_stmt = mysqli_stmt_init($connect);
if(!mysqli_stmt_prepare($update_compl_with_active_stmt, $update_compl_with_active_sql)) {
echo "Statement 2 Failed";
} else {
mysqli_stmt_bind_param($update_compl_with_active_stmt, "si", $updated_cda_str, $user_data['id']);
mysqli_stmt_execute($update_compl_with_active_stmt);
$set_active_zero_sql = "UPDATE `nations` SET `active_da` = ? WHERE `nations`.`user_id` = ?;";
$set_active_zero_stmt = mysqli_stmt_init($connect);
$zero = 0;
if(!mysqli_stmt_prepare($set_active_zero_stmt, $set_active_zero_sql)) {
echo "Statement 2 Failed";
} else {
mysqli_stmt_bind_param($set_active_zero_stmt, "ii", $zero, $user_data['id']);
mysqli_stmt_execute($set_active_zero_stmt);
}
mysqli_stmt_close($set_active_zero_stmt);
}
mysqli_stmt_close($update_compl_with_active_stmt);
mysqli_close($connect);
}
Here is my table before the function is run:
Before
Table after function has run:
After
When run, the debugging echos I used to check to see if the 'active_da' is set correctly produces this result (the 4 is the button ID, they are just triggers for the function for now):
Results from echo
My question is, how can I just simply transfer the 'active_da' column onto the end of the 'completed_da' column without adding that extra zero?
EDIT: I believe this is the query that's throwing it off
$set_active_zero_sql = "UPDATE `nations` SET `active_da` = ? WHERE `nations`.`user_id` = ?;";
$set_active_zero_stmt = mysqli_stmt_init($connect);
$zero = 0;
if(!mysqli_stmt_prepare($set_active_zero_stmt, $set_active_zero_sql)) {
echo "Statement 2 Failed";
} else {
mysqli_stmt_bind_param($set_active_zero_stmt, "ii", $zero, $user_data['id']);
mysqli_stmt_execute($set_active_zero_stmt);
}

Related

How to Update SQL Table Where condition is True

PROBLEM: I am trying to UPDATE table data with a "forgot password key" where the email field matches the user's form input on a previous page.
I want to make sure the user's input is sanitized and a match can be found in the database.
ERROR: The code does not update the ForgotKey Field in my Database
Here is my code, error is happening on line 7 where stated in the comment.
$ForgotKeyLength = 9;
$ForgotKeyString = "123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$ForgotKey = substr(str_shuffle($ForgotKeyString), 0, $ForgotKeyLength); //shuffle String, start with 0, 9 characters long
$sql = "UPDATE UserTable SET ForgotKey = ".$ForgotKey." WHERE Email = ? ";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../forgot.php?error2"); // THE ERROR HAPPENS HERE, UNABLE TO PREP STATEMENT
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $Email);
mysqli_stmt_execute($stmt); // I believe this line should update the table
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
//success: send user their email from here
$variable = $row['Email'];
}
else {
header("Location: ../forgot.php?error5");
exit();
}
}

Insert Data within a loop and echo only once

i have a php script with a sql query that is inside a foreach loop and if the query succeed to run it should echo "Success" but since its inside a loop it echo "success" multiple times but i wish to only echo "success" once. I have seen other similar threads here and i have looked at those and tried solve my problem from those threads but i have not been able to solve this problem from any other threads so please dont mark this as a duplicate.
Anyway, Here is my code
<?php
session_start();
include('../../config/dbconf.php');
foreach($_POST['entry'] as $entryid) {
$stmt = $authconn->prepare("UPDATE account SET dp = dp - ? WHERE username = ?");
$stmt->bind_param("is", $_POST['price'], $_SESSION['classicusr']);
if($stmt->execute()) {
echo "Success";
}else{
echo "Failed";
}
}
?>
You could try something like this?
Also, there is no need to prepare for each iteration of the loop.
<?php
session_start();
include('../../config/dbconf.php');
$bError = false;
$authconn->prepare("UPDATE account SET dp = dp - ? WHERE username = ?");
foreach($_POST['entry'] as $entryid) {
$stmt = $stmt->bind_param("is", $_POST['price'], $_SESSION['classicusr']);
try{
if(!$stmt->execute()) {
$bError = true;
// optional break and do not process further
// break;
$stmt = $stmt->errorInfo()
}
}catch (PDOException Exception){
$bError = true;
// additional erorr logging here. Could add to a delimetered string to report on later } }
echo ($bError ? 'Failure' : 'Success' );
?>
Seeing as you're not saying anything about the Failed statement, something like this might do the trick. All it requires is setting a simple flag.
<?php
session_start();
include('../../config/dbconf.php');
$feedbackGiven = FALSE;
foreach($_POST['entry'] as $entryid) {
$stmt = $authconn->prepare("UPDATE account SET dp = dp - ? WHERE username = ?");
$stmt->bind_param("is", $_POST['price'], $_SESSION['classicusr']);
if($stmt->execute()) {
if (!$feedbackGiven)
{
echo "Success";
$feedbackGiven = TRUE;
}
}else{
echo "Failed";
}
}
?>

PDO - Test Of Empty Results

I have a query that should look for an entry. If it's not in the database then enter in the data. Otherwise it returns back the data and they can update any fields. If there is an entry it will be only one. This works great if the entry is in the table. But I've tried checking for empty rows, doing row_count, etc and doesn't seem to work. Right now I just have this in the code(sanitized to remove company table information):
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
$result1 = $conn1->query($query1);
$conn1 = null;
if($result1==null)
{
echo "Result is null</p>\n";
return 0;
}
else
{
echo "Result is not null</p>\n";
return $result1;
}
If I take out the if check what I seem to get back is if it's found it returns the values correctly. If it's not found the result seems to be the query string itself. The check doesn't work. Probably because it returns back the query string if it's not found.
I know it's something simple but just haven't found it.
// if available in database
$query="SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."'";
$qnt = $conn1->query($query);
$coun = count($qnt->fetchAll());
if($coun > 0){
// available
echo "Result is available</p>\n";
}else{
//not available
echo "Result is not available</p>\n";
}
i Think you need something like this.
if this is not working fine, try another aproach
$queryi = $conn1->prepare("SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."' ");
$queryi->execute();
$qn= $queryi->fetchAll(PDO::FETCH_ASSOC);
foreach ($qn as $row => $data) {
$in_use = $data['Number'];
//echo $in_use ;
}
// evaluate
if($in_use == NULL){
//not avilable
}else{
// available
}
I suggest doing something like this:
Establish your query
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
See if there's a result for the query, and no error
if ($res = $conn1->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
After some trial and error I got this to work:
$result1 = $conn1->query($query1);
$count = $result1->fetchColumn();
if($count == "")
{
// echo "Result is null</p>\n";
return "0";
}
else
{
// echo "Result is not null</p>\n";
$result1 = $conn1->query($query1);
return $result1;
}
I had to change the setup to include:
$conn1->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);
Probably not a clean way but it works for now. Thanks for all the help.

Using transactions for queries which have dependant results

Here is my script structure:
try {
$dbh_conn->beginTransaction();
$stmt1 = $dbh_conn->prepare("SELECT user_id FROM activate_account WHERE token = ?");
$stmt1->execute(array($validate_activate_token));
$num_rows = $stmt1->fetch(PDO::FETCH_ASSOC);
if($num_rows) {
$user_id = $num_rows['user_id'];
$stmt2 = $dbh_conn->prepare("UPDATE users SET active = 1 WHERE id = ?");
$stmt2->execute(array($user_id));
$updated = $stmt2->rowCount();
if ( $updated > 0 ){
$stmt3 = $dbh_conn->prepare("DELETE FROM activate_account WHERE token = ?");
$stmt3->execute(array($validate_activate_token));
$status = "all fine";
} else {
$status = "first problem";
}
} else {
$status = "second problem";
}
$dbh_conn->commit();
echo $status;
die;
} catch(PDOException $e) {
$dbh_conn->rollBack();
$status = "third problem";
echo $status;
die;
}
The result of my code always is second problem. Why? And how can I rewrite my code to fix it?
Note that I've tested this condition if($num_rows) { separately (in another script singly) and it is true, but when I write it into script above, it is always false.
The purpose of transactions is to make sure that queries that must happen together are never broken up. In your use case, the first query can be executed in isolation with no downside.
Put the last two in a transaction, but leave the first alone. If the first fails, just don't run the other two.
If the first succeeds but one of the other two (in the transaction) fails so that neither of the two is committed, you're no worse off for having executed the first.

Cant track error cause in PHP page updating a MS SQL database

Simple PHP page (I'm no PHP expert, just learning) to update a MS SQL database. The following code generates an error that I dont know how to solve.
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE USERID='".$_REQUEST['user_id']."';";
if ($result = odbc_exec($dbconnect, $query)) {
echo "// Success!";
}
else {
echo "// Failure!";
}
odbc_close($dbconnect);
//End Update
This fails every time in the "if ($result ..." section
However, if I run virtually the same code
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL = '89990.jpg' WHERE USERID='80'";
if ($result = odbc_exec($dbconnect, $query)) {
// Success!
}
else {
// Failure!
}
odbc_close($dbconnect);
//End Update
It works just fine. I have echoed the $query string to the screen and the string is the same for both. I can't figure out why it fails in one and not the other?
Also weird is when I use a parameterized query such as
include '/connections/SFU.php';
$query = "UPDATE dbo.Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = $_REQUEST['user_id'];
$fn = $file["name"];
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
The query fails in the prepare section above, but fails in the odbc_exec section below:
include '/connections/SFU.php';
$query = "UPDATE Person SET PhotoURL=? WHERE USERID=?";
if ($res = odbc_prepare($dbconnect,$query)) {
echo "Prepare Success";
} else {
echo "Prepare Failed".odbc_errormsg();
}
$uid = "80";
$fn = "samplefile.jpg";
echo "query=".$query." userid=".$uid." filename=".$fn;
if ($result = odbc_exec($res, array($fn, $uid))) {
echo "// Success!";
}
else {
echo odbc_errormsg();
echo "// Failure!";
}
odbc_close($dbconnect);
In all cases I do not get any odbc_errormsg ().
Remove the extra ; from your query.
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id']."';";
^
So your query should be,
$query = "UPDATE Person SET PhotoURL = '".$file["name"]."' WHERE
USERID='".$_REQUEST['user_id'];
Also have practice of using odbc_errormsg() so you can have a better idea why your query gets failed.
Warning: Your code is vulnerable to sql injection attacks!

Categories