i'm trying to get this script to update my enum column 'read_message' in my 'ptb_messages' table but it just doesn't do anything. the rest of the script works fine but it's just ignoring the request to update 'read_message from 1 to 0.
can someone please show me where im going wrong? thanks
<?php
session_start();
include 'includes/_config/connection.php';
$subject = $_POST['subject'];
$message_id=$_GET['to'];
$textarea = $_POST['textarea'];
$query = mysql_query("SELECT content FROM ptb_messages WHERE id='".$message_id."'");
$results=mysql_fetch_array($query);
$result=$results['0'];
if($result && $textarea) {
$sql = mysql_query("UPDATE ptb_messages SET content ='".addslashes($textarea)."' WHERE id='".$message_id."'");
$sql = mysql_query("UPDATE ptb_messages SET date_sent = LOCALTIME WHERE id='".$message_id."'");
$query = mysql_query("SELECT suibject FROM ptb_messages WHERE id='".$message_id."'");
$sql = mysql_query("UPDATE ptb_messages SET subject = IF(subject LIKE '%:reply', subject, CONCAT(subject, ':reply')) WHERE id='".$message_id."'");
$sql = mysql_query("UPDATE ptb_messages SET read_message = '0' WHERE id=".$message_id."");
$_SESSION['message_sent']="<div class=\"message_sent\"></div>";
header("Location: {$_SERVER['HTTP_REFERER']}#confirm");
}
?>
You're hitting an edge case in MySQL. enum fields can have their values to referred to by the actual value, or their INDEX in the list of allowable values. You're trying to use 0, which MySQL is interpreting as index 0 of the list, which internally is the empty string.
e.g.
myfield ENUM('one', 'two', 'three')
myfield = 'two' => 'two'
myfield = 1 => 'one'
myfield = 0 => '', not in list, ignore...
If you just need a 0/1 value for a field, why not use an actual BIT field, which is already 0/1/null-only? Using enums for purely numeric values just runs into this value-v.s.-index problem.
Related
I have a form that POST value keeps coming as "" empty string into a unique SQL field.
It has to be unique as the field is optional but jet it can not have 2 same values. The unique value does allow null multiple values.
I don't even want to say what I tried to do, I'm trying to fix this for last few days.
Closest that I got is putting '$OIB'=IF('$OIB'='',NULL,'$OIB' into NSERT INTO statement, then i get null values into a database but for some reason when the number is entered into OIB form field it puts number 1 into a database...
$result = mysqli_query($conn, "SELECT OIB, NAZIV FROM STRANKEP WHERE OIB = '$OIB' OR NAZIV = '$NAZIV'");
if(mysqli_num_rows($result) == 0) {
// row not found, do stuff...
$sql = "INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES ('$NAZIV', CASE WHEN '$OIB' = '' THEN 'NULL', '$EMAIL', '$ADRESA', '$TELEFON')";
$query = mysqli_query($conn, $sql);
This solution gets me null but not the real $OIB when entered into form, it just puts number 1.
$result = mysqli_query($conn, "SELECT OIB, NAZIV FROM STRANKEP WHERE OIB = '$OIB' OR NAZIV = '$NAZIV'");
if(mysqli_num_rows($result) == 0) {
// row not found, do stuff...
$sql = "INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES ('$NAZIV', '$OIB'=IF('$OIB'='',NULL,'$OIB'), '$EMAIL', '$ADRESA', '$TELEFON')";
$query = mysqli_query($conn, $sql);
Thank you in advance for the help.
Try
CASE '$OIB' WHEN '' THEN NULL ELSE '$OIB' END
You can use also IF Clause
Like so
INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES
('$NAZIV', IF('$OIB' = '', NULL,'$OIB'), '$EMAIL', '$ADRESA', '$TELEFON');
But as mentioned in my comment use prepared statements like in PDO https://phpdelusions.net/pdo#prepared
I would recommend nullif(). It is a built-in standard function to do exactly this:
nullif(?, '')
Note: Do not munge queries with constant values. That makes the code subject to SQL injection attacks. And it can introduce very hard-to-debug errors. Use parameters!
I want to update members_roosevelt table ACCOUNT column starting with 3000+ value I also want to update ACCOUNT column on loan_roosevelt table that is related to my member_roosevelt. What's wrong with my query? Thank you!
$query1 = "SELECT ACCOUNT
FROM
`members_roosevelt`";
$result_q1 = $link->query($query1) or die($link->error);
while ($obj = $result_q1->fetch_object()) {
$members[] = $obj->ACCOUNT;
}
$ids = implode(',', $members);
$sql = "UPDATE `members_roosevelt` as `memb`
JOIN `loan_roosevelt` as `loan`
ON `memb`.`ACCOUNT` = `loan`.`ACCOUNT`
SET
(`memb`.`ACCOUNT`,
`loan`.`ACCOUNT`) = CASE ACCOUNT";
foreach ($members as $id => $ordinal) {
$sql .= sprintf("WHEN %d THEN %d ", $ordinal, (3000+$id));
}
$sql .= "END WHERE memb.ACCOUNT IN ($ids)";
$link->query($sql) or die($link->error);
SET (`memb`.`ACCOUNT`, `loan`.`ACCOUNT`) = CASE ACCOUNT...
This is simply not part of SQL syntax. You can't set two columns at a time like this. The left side of an assignment operator must be one column.
A better solution is to use a session variable.
SET #acct = 3000;
UPDATE members_roosevelt as memb
JOIN loan_roosevelt as loan
ON memb.ACCOUNT = loan.ACCOUNT
SET memb.ACCOUNT = (#acct:=#acct+1),
loan.ACCOUNT = (#acct);
This way you don't have to run the SELECT query at all, and you don't have to create a huge UPDATE statement with potentially thousands of WHEN clauses.
Demo: SQLFiddle
I am very confused about this (returning false):
$sql = "SELECT * from tbl_user WHERE group = 'abc'";
$res = mysql_query($sql);
if(mysql_num_rows($res) > 0) {
$response = array('status' => '1');
} else {
$response = array('status' => '0'); // ---> what I get back
die("Query failed");
}
...despite the fact the field group is present in mySQL database. Even more strange is that the following return the value of group:
$SQL = "SELECT * FROM tbl_user";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['group']; // ---> returns 'abc'
When I execute a WHERE clause with every other fields of my table excepting group (for example WHERE name = 'ex1' AND ID=1 AND isAllowed=0 (and so on...), everything is fine. As soon as I insert group = 'abc', I get nothing...
This makes me mad. If anyone could help... (I am running a local server with MAMP).
Thanks a lot!
The issue is that group is a reserved word in SQL.
For MySql you need to escape it with backticks
`group`
So your query would be
$sql = "SELECT * from tbl_user WHERE `group` = 'abc'";
I am having an issue with inserting an array of information into a mysql database. Basically I built a sortable gallery similar to Facebook's photo albums that can be arranged by moving the div to a new spot with jquery's sortable function.
I am using Ajax to call a php file which will inser the new order of the div's into the DB. The information is being passed correctly, it is just not being inserted correctly.
The error I am receiving is:
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 'Array' at line 1
The Php code is:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
If I remove the mysql_query function and just do a print_r, I get:
Array
(
[0] => UPDATE table SET order = '0' WHERE id = '2'
[1] => UPDATE table SET order = '1' WHERE id = '4'
[2] => UPDATE table SET order = '2' WHERE id = '3'
[3] => UPDATE table SET order = '3' WHERE id = '1'
[4] => UPDATE table SET order = '4' WHERE id = '5'
[5] => UPDATE table SET order = '5' WHERE id = '6'
)
This is the first time I have tried to do something like this. Any help would be great.
Thank you in advance for the help!
In mysql_query($sql) $sql is an array, therefore it's value is simply Array. When you assign $sql[] = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'"; simply make this line $sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";. That should solve your problem.
EDIT:
You can leave the [] and simply remove the mysql_query from where it is. After your foreach list item, add this:
foreach($sql as $query) {
mysql_query($query);
}
Sounds like there is some confusion about what the [] operator does. You use [] when you want to append an element to the end of an existing array.
For example:
$sql = array();
$sql[] = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will produce the error you are seeing
Versus:
$sql = 'UPDATE table SET order = "0" WHERE id = "2"';
mysql_query($sql); // this will work
You should rewrite your code as such:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) {
$sql = "UPDATE table SET order = '{$position}' WHERE id = '{$item}'";
mysql_query($sql) or die(mysql_error());
}
}
That will do what you are intending. However, this is still not a good idea, since you are passing untrusted $_GET data directly to the database. I could, for example, call your script with a string like:
http://yoursite.com/yourscript.php?listItem=1'%3B%20DROP%20TABLE%20yourtable%3B
Since the value of listItem is going directly to the database -- and the $item >= 1 check is insufficient, since PHP will evaluate a string as an integer if it begins with numeric data -- all I have to do is add a single quote to terminate the previous query, and I am then free to inject whatever SQL command I'd like; this is a basic SQL injection attack. Whenever you write database-touching code, you should cleanse any input that might be going to the database. A final version of your code might look like:
foreach ($_GET['listItem'] as $position => $item) {
if ($item >= 1) { // this check may or may not be needed depending on its purpose
$sql = 'UPDATE table SET order = "' . mysql_real_escape_string($position) . '" WHERE id = "' . mysql_real_escape_string($item) . '"';
mysql_query($sql) or die(mysql_error());
}
}
There are other ways to cleanse input data as well, that is just one of them. Hope that helps.
This makes no sense!
The update query only actually updates if the value is an INT (yes it is defined as text).
The INSERT which has the same variables works with type of value!
mysql_query("UPDATE `atuam_mae`.`missoes` SET `mensagemdeuser` = $message WHERE `missoes`.`id` =$idmissao;");
mysql_query("INSERT INTO `atuam_mae`.`concelhos` (`id` ,`tempo` ,`userid` ,`concelho`) VALUES (NULL , CURRENT_TIMESTAMP , $user , '$message');");
That is because you are not enclosing your input variable in quotes:
"UPDATE `atuam_mae`.`missoes`
SET `mensagemdeuser` = '$message'
WHERE `missoes`.`id` = '$idmissao';"
NB. Don't do this and use prepared statements instead!
$stmt = $db->prepare('UPDATE `atuam_mae`.`missoes`
SET `mensagemdeuser` = :message
WHERE `missoes`.`id` = :id');
$stmt->execute(array(':message' => $message, ':id' => $idmissao));
I am not sure I understand what you meant but try putting values (right of the =) between single quotes this way:
mysql_query("UPDATE `atuam_mae`.`missoes` SET `mensagemdeuser` = '$message' WHERE `missoes`.`id` ='$idmissao';");