Completely bizarre behaviour on MYSQLi update - php

A warning up front, this project is part of a reporting system for workers looking after people with some profound disabilities and there is some unsavoury language that I don't use in jest and wouldn't in such a forum unless it was completely pertinent. No offense is meant.
I don't know if I even expect an answer to this because it is so completely strange, but here goes... I have a pretty simple form editing a text field in a mysql database. The update code couldn't be simpler;
(after connecting to the database)
$stmt = $mysqli->prepare("UPDATE rep_evening SET rppe_notes = ? WHERE rppe_mrep = ?");
$stmt->bind_param('si', $_POST['enotes'], $_POST['repid']);
$stmt->execute();
$stmt->close();
header("Location: ../reports.php");
The code is probably pointless because it all works perfectly well UNTIL the words 'suck dicks' is somewhere in the text. Then it throws a 403 error which is seemingly triggered on the header return because the update works. I thought perhaps somebody had put a profanity filter in but if they did it's pretty useless because it doesn't matter what else is in there, and believe me there's some pretty unsavoury stuff, just those two words, with the plural on the latter word - the singular doesn't fire the error. The 2 words can be separated by up to 3 words and trigger the 403, but no more than 3.
There's nothing in error logs, no clues anywhere but it can be replicated any number of times.
MYSQL V5.6.30, PHP 5.4 if that's of interest.
Edit...
Here's the full processing page, there's 3 sections to the report and an approval tag for it to be viewed beyond admins;
<?php
include ('../includes/dbconn.php');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("UPDATE rep_day SET rppm_notes = ? WHERE rppm_mrep = ?");
$stmt->bind_param('si', $_POST['mnotes'], $_POST['repid']);
$stmt->execute();
$stmt->close();
$stmt = $mysqli->prepare("UPDATE rep_evening SET rppe_notes = ? WHERE rppe_mrep = ?");
$stmt->bind_param('si', $_POST['enotes'], $_POST['repid']);
$stmt->execute();
$stmt->close();
$stmt = $mysqli->prepare("UPDATE rep_overnight SET rppo_notes = ? WHERE rppo_mrep = ?");
$stmt->bind_param('si', $_POST['onotes'], $_POST['repid']);
$stmt->execute();
$stmt->close();
$stmt = $mysqli->prepare("UPDATE mreport SET mrep_approved = ? WHERE mrep_id = ?");
$stmt->bind_param('si', $_POST['approved'], $_POST['repid']);
$stmt->execute();
$stmt->close();
header("Location: ../reports.php");
?>

Related

simple update and insert mysqli in php code can not be executed [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 5 years ago.
This little piece of code should be very easy basic coding, yet it doesn't work. The problem is within the INSERT / UPDATE code, because if I delete those and just echo simple text inside of the if/else code everything works just fine.
This is the code I have, whichs gives a HTTP ERROR 500.
$sql2 = mysqli_query($mysqli, "SELECT * FROM koppel WHERE userid = ".$_GET['userid']." AND msgid = ".$_GET['msgid']."");
$row = mysqli_fetch_assoc($sql2);
$check = $_GET['check'];
$msgid = $_GET['msgid'];
$userid = $_GET['userid'];
$ja = 'ja';
$nee = 'nee';
$tabel_content = $row['check'];
$tabel_id = $row['id'];
if ($tabel_content == $ja){
$stmt = $mysqli->prepare("UPDATE koppel SET check = ? WHERE id = ?");
$stmt->bind_param('si',
$nee,
$tabel_id);
$stmt->execute();
$stmt->close();
} elseif ($tabel_content == $nee){
$stmt = $mysqli->prepare("UPDATE koppel SET check = ? WHERE id = ?");
$stmt->bind_param('si',
$ja,
$tabel_id);
$stmt->execute();
$stmt->close();
} else {
$stmt = $mysqli->prepare("INSERT INTO koppel(userid,
msgid,check) VALUES (?, ?, ?)");
$stmt->bind_param('iis', $userid,
$msgid,
$check);
$stmt->execute();
$stmt->close();
}
What am I missing?
I don't see any error there, but make sure $mysqli is a valid mysqli connection to your database.
To debug your problem, try checking your server error logs (they will show the cause of your 500 error, and in which line) or try removing each part of your code until you understand exactly which line is failing.
You can also move all your "execute" and "close" calls to be below the if/elseif/else structure, as it always gets executed, to avoid repeating code.
Also "tabel" should be spelled "table".

Unable to perform Update sql from php

The following is my code
try {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$sql = "UPDATE usermaster SET Password=?, UserName=?, OwnerOrEmp=?, DBName=?, DeleteFlag=?, UpdateDate=? WHERE UserId = ?";
$sql = "UPDATE usermaster SET Password=:password, UserName=:userName, OwnerOrEmp=:ownerOrEmp, DBName=:dBName, DeleteFlag=:deleteFlag, UpdateDate=:updateDate WHERE UserId = :id";
$q = $pdo->prepare($sql);
$q->bindParam(':id', $id, PDO::PARAM_STR, 8);
$q->bindParam(':userName', $name);
$q->bindParam(':password', $pass);
$q->bindParam(':ownerOrEmp', $ownEmp);
$q->bindParam(':dBName', $dbName);
$q->bindParam(':deleteFlag', $delEmp);
$q->bindParam(':updateDate', $curr_date);
$q = $pdo->prepare($sql);
$q->execute(array($pass,$name,$ownEmp,$dbName,$delEmp,$curr_date, $id));
Database::connect();
}catch(PDOException $e){
//die($e->getMessage());
$db_error = "".$e->getMessage();
}
header("Location: ShainIndex.php");
}
Request your kind insight, this piece of code alone does not get executed and update is not executed...Thanks in advance.
your preparing same query twice
$q->bindParam(':updateDate', $curr_date);
// $q = $pdo->prepare($sql); //comment this line
$q->execute(array($pass,$name,$ownEmp,$dbName,$delEmp,$curr_date, $id));
I finally began to debug each and every single variables value being inserted, as shown in the above bindParam(). It turned out that by default or due to some string handling there happened to a space(" ") being inserted into many many of the values of those variables.
So, what this space was causing was, that it did not allow the value to be matched on the database to the inputed data coming from the view.
Due to which especially the "id" field receive values with spaces...like " 00100001" although it is not easily visible it never matched with "00100001" value in the db's table.
Thus, this took me the whole day and almost cost me my job. In some place a small "-" broke down an entire satellite launching rocket.
So, I am in a way blogging my "Word of Caution" to all those whose life ticks on one tiny bit of characters.
Thanks to all those who provided their valuable inputs and time.

MySQLi UPDATE isn't working.

For some reason I can't get UPDATE to work, after hours of googling I can't seem to find a working code.
$stmt = $con->prepare("UPDATE user_settings SET accept_emails = ? WHERE user= '$user'");
$stmt->bind_param('s', '0');
$stmt->execute();
$stmt->close();
Trying to update via Ajax, keeps returning 500 Server Error. Should I just use the old MySQL way?
i am pretty sure you can't use a literal in bind only variables.
This is what you should use.
$var="0";
$stmt = $con->prepare("UPDATE user_settings SET accept_emails = ? WHERE user=?");
$stmt->bind_param('ss',$var,$user);
$stmt->execute();
$stmt->close();

->num_rows doesn't work correctly [duplicate]

This question already has answers here:
PHP MYSQLI number of rows doesnt work no errors
(3 answers)
Closed 6 years ago.
I don't understand why $amountOfUsers is showing as 0?
This used to work before I moved to the bind_param function... I was only using query() instad of prepare. But this is a lot safer, I just have trouble understand why this doesn't work, and how to fix it.
$stmt = $mysqli->prepare("SELECT id, expire, status, username FROM username WHERE username= ?");
$stmt->bind_param('s', $username);
$stmt->execute();
//Counting results. 0 = Invalid, 1 = Valid
$amountOfUsers = $stmt->num_rows;
The error I am getting is: $amountOfUsers isn't counting the number of results properly.
$stmt = $mysqli->prepare("SELECT id, expire, status, username FROM username WHERE username= ?");
$stmt->bind_param('s', $username);
$stmt->execute();
// Store the result (so you can get the properties, like num_rows)
$stmt->store_result();
// Get the number of rows
$amountOfRows = $stmt->num_rows;
// Bind the result to variables
$stmt->bind_result($id, $expire, $status, $db_username);
// Process the variables
while($stmt->fetch()) {
printf("%d %s %s %s\n", $id, $expire, $status, $db_username);
}
Sometimes things don't go according to plan. Checking result codes and errors available in your library is usually more efficient for troubleshooting than asking strangers, but hopefully this stranger can help... choose one of these patterns:
A:
$result = $stmt->execute();
if (!$result) { /* handle errors */ }
B:
$stmt->execute();
if ($stmt->errno != 0) { /* handle errors */ }
C (for development troubleshooting only, not code you would leave around):
$stmt->execute();
print_r($stmt->error_list);
More info here and associated pages:
http://www.php.net/manual/en/mysqli-stmt.errno.php
I would never in my life understand why php users are so inclined to the number of rows returned.
Especially if used only as a flag... if any data returned!
Why not to take the very returned data and see?
$sql ="SELECT id, expire, status, username FROM username WHERE username= ?s";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if ($row)
{
// do whatever
}
I would never understand an inclination to long and windy codes as well.
Why not to get yourself an abstraction library and get everything in one single line?
$sql = "SELECT id, expire, status, username FROM username WHERE username= ?";
if ($row = $db->getRow($sql))
{
// do whatever
}

mySQLi Prepared Statement Select with Escape Characters

I am trying to select from a mySQL table using prepared statements. The select critera is user form input, so I am binding this variable and using prepared statements. Below is the code:
$sql_query = "SELECT first_name_id from first_names WHERE first_name = ?";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == '1') {
$stmt->bind_result($_SESSION['first_name_id']);
$stmt->fetch();
} else {
$stmt->close();
$sql_query = "INSERT INTO first_names (first_name) VALUES (?)";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$_SESSION['first_name_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
Obviously my code is just determining whether or not the first_name already exists in the first_names table. If it does, it returns the corresponding ID (first_name_id). Otherwise, the code inserts the new first_name into the first_names table and gets the insert_id.
The problem is when a user enters a name with an escape character ('Henry's). Not really likely with first names but certainly employers. When this occurs, the code does not execute (no select or insert activity in the log files). So it seems like mySQL is ignoring the code due to an escape character in the variable.
How can I fix this issue? Is my code above efficient and correct for the task?
Issue #2. The code then continues with another insert or update, as shown in the code below:
if (empty($_SESSION['personal_id'])) {
$sql_query = "INSERT INTO personal_info (first_name_id, start_timestamp) VALUES (?, NOW())";
} else {
$sql_query = "UPDATE personal_info SET first_name_id = ? WHERE personal_info = '$_SESSION[personal_id]'";
}
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('i', $_SESSION['first_name_id']);
$stmt->execute();
if (empty($_SESSION['personal_id'])) {
$_SESSION['personal_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
The issue with the code above is that I cannot get it to work at all. I am not sure if there is some conflict with the first part of the script, but I have tried everything to get it to work. There are no PHP errors and there are no inserts or updates showing in the mySQL log files from this code. It appears that the bind_param line in the code may be where the script is dying...
Any help would be very much appreciated.
you should validate/escape user input before sending it to the db.
checkout this mysql-real-escape-string()

Categories