Issue with alphanumerics using a variable to populate an SQL db - php

Trying to update a mysql db by clicking a close button and updating the status attribute with "0" and echo'ing a "closed" verbiage. The current code I inherited from someone else updates the db if the job number is only numeric integers. When the job number is an alphanumeric or just alpha I get an error message:
UPDATE not successful: Unknown column 'test5' in 'where clause'
Initial updateTable comes from this function in a functions.php file:
function updateTable($table, $update, $where){
$query = ("UPDATE $table "."SET $update "."WHERE $where ");
$result = mysql_query($query)
or die("UPDATE not successful: " . mysql_error());
}
The closing of the record and update to mysql is done with this code:
if($_SESSION['login']){
include("functions.php");
$currentPOJO = $_GET["pojo"];
dbConnect();
$where = "pojo_number=".$currentPOJO;
updateTable("records", "status=0", $where);
echo "closed";
}
I have tried several changes with no luck. What am I missing?
Again updating a column in a db with "0" to signify closure of a record. The job number or "pojo" has to be able to have both alpha and numeric chars.
NOTE - My mysql db has the "status" attribute/column set to, varChar(35).
Thanks for any help possible.

Looks like you're missing a set of quotes:
$where = "pojo_number='". $currentPOJO ."'";
That makes the query change from:
WHERE pojo_number=test5 to WHERE pojo_number='test5'

Related

Why does this UPDATE query not update my table?

I am trying to code a user system. I am having an issue with the activation part. I can select and insert data to my table but now I am trying to create an update statement and got stuck.
<?PHP
include "db_settings.php";
$stmt = $dbcon->prepare("UPDATE 'Kullanicilar' SET 'Aktivasyon' = ? WHERE 'KullaniciID'=?");
// execute the query
$stmt->execute(array('1','5'));
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
?>
And I am getting error as:
"0 records UPDATED successfully".
This is my table; http://i.imgur.com/PL2eD80.png
I have tried by changing my 'Aktivasyon' type int to char but it also does not work.
EDIT:
I am trying to make this a function;
function dataUpdate($tableName, $updateRow, $updateValue, $conditonRow, $conditionValue)
{
include "db_settings.php";
$q = $dbcon->prepare("UPDATE $tableName SET $updateRow= ? WHERE $conditonRow= ?");
$q->execute(array($updateValue,$conditionValue));
}
I also try this :
...
$q = $dbcon->prepare("UPDATE `$tableName` SET `$updateRow`= ? WHERE `$conditonRow`= ?");
...
How can I make this statement work?
You are using wrong quotes. You are basically saying "update this table, set this string to something when the string KullaniciID equals the string 5" which of course never is true.
You should use backticks ` if you want to specify column names. Then your query would work. Usually you don't even need those, but for some reason MySQL world is always adding them.
So to clarify, this is a string: 'KullaniciID' and this is a column name: `KullaniciID`.
Also you should not send integers as strings. It causes extra conversions or even errors with more strict databases.

MYSQL DELETE query not affecting rows

Here is a function I have in my php file
function deleteLocation() {
global $con;
$val = $_POST['id'];
$escaped = mysqli_real_escape_string($con,$val);
$sql = "DELETE FROM settings WHERE value = '".$escaped."'";
if(!mysqli_query($con,$sql)){
die("Query failed:" . mysqli_error($con));
} else {
die("DELETE FROM settings WHERE value = '".$escaped."' / num rows affected: " . mysqli_affected_rows($con));
}
}
Here is the text that is returned on the page
DELETE FROM settings WHERE value = 'asdasd ' / num rows affected: 0
If I take the first part, and run it on my phpmyadmin page,
DELETE FROM settings WHERE value = 'asdasd '
it will correctly delete the row, but as you can see from the output, 0 rows are affected when the script is run on the page.
If anyone can help to fix this I will be very grateful.
PS: The connection string and user permissions are indeed set up correctly, because every other function in this file works properly
EDIT: Got it, the space at the end of the string was a newline character that was sent from my javascript.
I tried re-creating your problem on my machine and the only time I get the same message as you is when that item was already deleted from the table (or when it wasn't there in the first place)
This was a pretty unique situation, so I don't know how much this would help other people but,
I had an array of strings that all had \n at the end, so I had to do
str[value] = str[value].trim();
foreach value in the array. It turns out that this was not a php problem, but rather js

How to get last Insert Id while logging the query using PHP-PDO

Recently I have been creating a function to record every changes in the database, simply I record it to a table.
Table backup_log: backupTableName, backupLastUpdate, backupLastupload
So, every time changed, its will record the date to "backup_log".
It's runs well, but I have problem when I need Last Insert Id, I using $orderid = $dbh->lastInsertId('orderId'); to get "last insert Id", but its return "0".
I figure out that the problem comes when I put querylog() function that runs another query while the query() function still also run. coz its using same PDO object.
So, any suggestion for me to able to get "last insert id", while runs querylog() ?
This is my code:
//$dbh is object of PDO connection
$sql = query("INSER INTO orders ...");
$orderid = $dbh->lastInsertId('orderId'); // table "orders"
function query($sql){
#this function is not the full version, just for example
global $dbh;
$query=$dbh->exec($sql);
querylog($sql); // Log every insert, delete and update query
}
function querylog($sql){
global $dbh; // PDO object
global $now;
//Table backup_log: backupTable, backupLastUpdate, backupLastupload
###### Log: for insert and update ########
#if the query too long, cut for 200 chars and convert them to array
$sql_clean_space=str_replace(array(" ",'`'),array(" ",''),$sql); //change double space to single space
if(strlen($sql_clean_space) > 200){
$sql_clean_space = substr($sql_clean_space, 0, 200); // get only 200 char
}
$sql_array=explode(" ", $sql_clean_space); //convert to array to get the command name, insert or update
$now_date=$now;
#save log
if(strtolower($sql_array[0])=='insert' or strtolower($sql_array[0])=='delete'){
#check whether the query is insert or update
$sqlx = "SELECT * FROM backup_log WHERE backupTable='".$sql_array[2]."'";
$query=$dbh->query($sqlx);
$check_row=$query->rowCount($query);
if($check_row){
$sql_log="UPDATE backup_log SET backupLastUpdate='$now' WHERE backupTable='". $sql_array[2] . "'";
}else{
$sql_log="INSERT INTO backup_log VALUES('".$sql_array[2]."', '$now_date','$now_date')";
}
}elseif(strtolower($sql_array[0])=='update'){
$sqlx = "SELECT * FROM backup_log WHERE backupTable='".$sql_array[1]."'";
$query=$dbh->query($sqlx);
$check_row=$query->rowCount($query);
if($check_row){
$sql_log="UPDATE backup_log SET backupLastUpdate='$now' WHERE backupTable='". $sql_array[1] . "'";
}else{
$sql_log="INSERT INTO backup_log VALUES('".$sql_array[1]."', '$now_date','$now_date')";
}
}
$query_log=$dbh->exec($sql_log);
####### End of log ######################
}
Maybe you can assign last insert id in query functions and it can be preserved while query executions. See my code below;
$sql = query("INSER INTO orders ...", 'orderId'); //$sql is equal to last insert id
$orderid = $sql
function query($sql, $specific_id_column){
#this function is not the full version, just for example
global $dbh;
$query=$dbh->exec($sql);
$last_id = $dbh->lastInsertId($specific_id_column);
querylog($sql); // Log every insert, delete and update query
return $last_id;
}

PHP update query, code revision

I have two functions on the same webpage, each of them will update one different table on the same database depending which button you press.
This function modifies one table and works:
function SaveMItem()
{
$DayOfWeekNumber = 0;
if ($_POST['selDayOfTheWeek'])
{$DayOfWeekNumber = $_POST['selDayOfTheWeek'];}
mysql_query("UPDATE tblMItem SET ItemText = '" . $_POST['txtFirstOne'] . "' WHERE MenuItemID = " . (1 + $DayOfWeekNumber));
echo "SaveMItem Ok";
}
function SavetblAnnouncement(){
mysql_query("UPDATE TblAnuncios SET Title=".$_POST['txtAnnouncementTitle']. ",Content=".$_POST['txtAnnouncementContent']." WHERE 1");
echo "Completed announcement" ;
}
When I press SaveMItem button I can see the message SaveMItem Ok and it saves new values on Table.
When I press SavetblAnnouncement button I can see the message Completed announcement but the table TblAnuncios will not get updated.
As this is on the same file, the Database is the same and the function SaveMItem is able to update the table I suppose the connexion to the DB is ok.
Can anyone let me know what am I doing wrong?
Thanks in advance.
You're missing quotes around the values.
$title = mysql_real_escape_string($_POST['txtAnnouncementTitle']);
$txt = mysql_real_escape_string($_POST['txtAnnouncementContent']);
mysql_query("UPDATE TblAnuncios SET Title='".$title. "',Content='".$txt."' WHERE 1");
You should also escape the string, both to prevent SQL injection and also to make the query correct if the title or text contains quote characters.

Unable to input numbers into MySQL using php statement

I am working on a website where an administrator can edit a schedule that they already created. They can click on any item on the schedule to edit it. For example, they can click on the shift start time and then it directs them to a page where they can update the value.
Unfortunately, I have not been able to get this to work for every value. It seems to be that the text values are working just fine, but I am getting a syntax error when it is a number.
Here is what I am using to update:
$type = $_GET['type'];
$value = $_GET['value'];
$week = $_GET['week'];
$newval = $_POST['newval'];
if(strlen($newval) > 0)
{
include '../dbinfo.php';
$type = $mysqli->real_escape_string($_POST['type']);
$week = $mysqli->real_escape_string($_POST['week']);
$tablename = $mysqli->real_escape_string("cs" . $_SESSION['squadron']);
$newval = $mysqli->real_escape_string($newval);
if((is_numeric($newval)))
{
$sql = "UPDATE $tablename SET $type=$newval WHERE week=$week";
}
else
{
$sql = "UPDATE $tablename SET $type='$newval' WHERE week=$week";
}
if($result = $mysqli->query($sql))
{
echo "Your specififed changed was completed successfully!<br>";
echo "<a href='edit.php?week=" . $week . "'>Continue editing</a>";
}
else
{
echo mysqli_error($result);
}
}
Changing a string results in the sql statement:
UPDATE cs14 SET shift_1_name='Test' WHERE week=1 (this works)
Changing a number results in the sql statement:
UPDATE cs14 SET shift_ 1_starttime=940 WHERE week=1 (this doesn't work)
It is giving me the MySQL error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1_starttime=940 WHERE week=1' at line 1
I have already researched this error, and I have checked the syntax over and over again. It doesn't work in phpmyadmin either. I have no idea what to check next!
Can anyone help me out with my syntax here??? Thanks!
At the numeric update query put quotes around,
$sql = "UPDATE $tablename SET $type='$newval' WHERE week='$week'";
The $type variable contains a space. Remove the space from it.
More specifically "shift_ 1_starttime" contains a space. Wherever your setting $type to "shift_ 1_starttime" remove the space from it. Or if thats how it is defined in the database surround it with backticks `
$sql = "UPDATE $tablename SET `$type`='$newval' WHERE week=$week";

Categories