I want to change data from a database but I keep getting errors and I just cannot find the mistake I made..
Here's the code:
if(isset($_POST['id'])) {
if(is_numeric($_POST['id'])) {
$change = pg_query($db, "SELECT * FROM azubi3 WHERE id = ".$_POST['id']."");
echo $change;
if($auto == "") {
$auto = "false";
}
else { $auto = "true"; }
$change = pg_query($db, "UPDATE azubi3 SET vorname = '".$_POST['prename']."', nachname = '".$_POST['name']."', auto = ".$auto.", auto_id = ".$_POST['auto_id'].", schuh_id = ".$_POST['schuh_id']." WHERE id = ".$_POST['id']."");
}
else { echo "ID muss eine Zahl sein!"; }
}
And that's the error i get:
Warning: pg_query(): Query failed: ERROR: syntax error at or near "," LINE 1: ...achname = 'Mustermüller', auto = false, auto_id = , schuh_id... ^ in /srv/www/htdocs/azubi2/test3.php on line 82
First thing your sql is vulenrable to injection, you should correct it.
For the sake of your question :
false is a reserved keyword, please use string around it:
$change = pg_query($db, "UPDATE azubi3 SET vorname = '".$_POST['prename']."', nachname = '".$_POST['name']."', auto = '".$auto."', auto_id = ".$_POST['auto_id'].", schuh_id = ".$_POST['schuh_id']." WHERE id = ".$_POST['id']."");
Related
How can I change one value or more values of choice? If I enter a single value, it works. Still, if I enter two values in two input fields, it doesn't work, showing me the following error.
Error updating record: You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax to use near 'nat = 'saf' WHERE id = '16'' at line 1
if (isset($_POST['modifica'])) {
$id = $_POST['id'];
$semaphore = false;
$sql = "UPDATE users SET ";
$fields = array('nume', 'nat', 'email', 'telefon');
foreach ($fields as $field) {
if (isset($_POST[$field]) and !empty($_POST[$field])) {
$var = ($_POST[$field]);
$sql .= $field." = '$var'";
$semaphore = true;
}
}
if ($semaphore) {
$sql .= " WHERE id = '$id'";
($sql);
}
if ($conn->query($sql) === true) {
echo "Record updated successfully";
} else {
echo "Error updating record: ".$conn->error;
}
$conn->close();
}
An inplementatiom aproach of #m-eriksson comments:
$sql = "UPDATE users SET nume = :nume, nat = :nat, email = :email, telefon = :telefon";
$fields = array('nume', 'nat', 'email', 'telefon');
if(count($fields) > 0 ){
$this->update($sql, $fields, $con)
$semaphore = true;
}
public function update ($sql, $fields, $con)
{
$update = $con->prepare($query);
return $update->execute($fields);
}
I'm trying to create a sign up form, it was working fine until I tried to add md5 to the password field set, I'm not sure why the Query failed. Any help would be much appreciated.
function sign_up(){
if(isset($_POST['register'])){
$c_email = escape_string($_POST['c_email']);
$c_name_first = escape_string($_POST['c_name_first']);
$c_name_last = escape_string($_POST['c_name_last']);
$c_pass = escape_string($_POST['c_pass']);
$c_image = escape_string($_FILES['c_image']['name']);
$c_image_tmp = escape_string($_FILES['c_image']['tmp_name']);
$c_address = escape_string($_POST['c_address']);
$c_address_details = escape_string($_POST['c_address_details']);
$c_city = escape_string($_POST['c_city']);
$c_state = escape_string($_POST['c_state']);
$c_zip = escape_string($_POST['c_zip']);
$c_contact = escape_string($_POST['c_phone']);
move_uploaded_file($c_image_tmp, "customer/customer_images/$c_image");
$query = query("SELECT customer_id FROM customers WHERE customer_email = '{$c_email}'");
confirm($query);
if(mysqli_num_rows($query) > 0){
set_message("This email or username is taken");
}else {
$insert_c = query("INSERT INTO customers (customer_firstname,customer_lastname,customer_address,c_addr_details,customer_email,customer_pass,customer_state,customer_city,customer_zip,customer_phone,customer_image) VALUES ('$c_name_first','$c_name_last','$c_address','$c_address_details','$c_email','$c_pass','$c_state','$c_city','$c_zip','$c_contact','$c_image')");
confirm($insert_c);
}
$query = "UPDATE user SET 'customer_pass' = '".md5(md5(last_id()).$c_pass)."' WHERE 'customer_id' = '".last_id()."'";
$send_update_query = query($query);
confirm($send_update_query);
set_message_success("Sign up successful!");
}
}
Try
$query = 'UPDATE user SET customer_pass = '.md5(md5(last_id()).$c_pass).' WHERE customer_id = '.last_id();
Check you string when you use " or '
The data present in the postgresql table isn't update any more. I want to overwrite the data. When I just use insert into, new data is added but the old data remains. I tried to use update but then I get errors. I would like to update all records. I think it's probably something with the syntax. But I can't find the problem.
Code
$dbname = "dbtest";
$host = "localhost";
$username = "postgres";
$password = "pasword";
$dbh = new PDO("pgsql:dbname=$dbname; host=$host", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$c = array("Human","Mouse","Rat","Hamster","SV40");
$b = array("Human HBO gene", "Mouse BB gene", "Human CCB gene", "SV40 TP gene", "Hamster TP53 gene");
$count=0;
foreach($c as $key => $d){
$e =$b[$key];
$name = $count++;
if (strpos($e, $d) !== FALSE) {
$match = $d;
$specie = $d;
$specie = str_replace("Human","Homo Sapiens",$specie);
$specie = str_replace("Mouse","Mus Musculus",$specie);
$specie = str_replace("Rat","Rattus norvegicus",$specie);
$Specie = str_replace("Hamster", "Mesocricetus Auratus",$specie);
$specie = str_replace("SV40","Simian virus 40",$specie);
}else{
$match = "0";
$specie = "0";
}
echo $match. " ". $specie. " ";
$var_id = $name;
$var_match = $match;
$var_full_name = $specie;
#$sql = "INSERT INTO species (id,match,full_name) VALUES ('".$var_id."','".$var_match ."','".$var_full_name."')";
$sql = "UPDATE species SET id = '".$var_id."', match = '".$var_match ."', full_name='".$var_full_name."'";
if ($dbh->query($sql)) {
echo "New Record Inserted Successfully!<br \>\n";
}else{
echo "Data not successfully Inserted.<br \>\n";
}
}
The error I get:
Fatal error: Uncaught PDOException: SQLSTATE[42601]: Syntax error: 7 ERROR: > syntax error at or near "Sapiens" LINE 1: ...species SET id = '0', match = Human, full_name=Homo Sapiens' ^ in /var/www/html/test/Insert.php:59 Stack trace: #0 /var/www/html/test/Insert.php(59): PDO->query('UPDATE species ...') #1 {main} thrown in /var/www/html/test/Insert.php on line 59
You should use a select query to determine if the value is new or old. If old update data, else insert data.
FUNCTION
function execute_query($query,$dbh){
if ($dbh->query($query)) {
return "New Record Inserted Successfully!<br \>\n";
}else{
return "Data not successfully Inserted.<br \>\n";
}
}
SELECT
$query = 'SELECT * FROM tbl '. 'WHERE "test1" = '.
"'".$var_test."'" . 'AND "test2" = '.
"'".$var_test2."'";
$stmt = $dbh->prepare($query);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$outcome = $stmt->fetch();
UPDATE
if ($outcome !== false){
$sql = "UPDATE tbl SET test1 = '".$var_test1."', test2 = '".$var_test2."',
test3 = '".$var_test3."'
"WHERE id = '".$var_id."' ";
execute_query($sql,$dbh);
INSERT
}else{
$sql = "INSERT INTO genes
(id,test1,test2,test3)
VALUES ('".$var_id."','".$var_test1 ."','".$var_test2."','".$var_test3."')";
execute_query($sql,$dbh);
}
When I use the following syntax, the error is gone. This query needs to be used to update.
$sql = "UPDATE species SET match ='".$var_match ."', full_name='".$var_full_name."' WHERE id = '".$var_id."' ";
Current update: I've cleaned up the code, and there are still some issues.
NOTE this code runs every 3 seconds. The outermost 'else' statement seems to run, setting the time to 0 in the database table, but then there is no activity.
After the initial time of running, the outermost 'else' statement should never run, and the time value stored under the user's alias should keep updating with the latest time stamp, but it just sits at '0'.
This is the JS that runs the php file:
//CHECK FOR NEW CHAT MESSAGES
setInterval(function()
{
$.post("chat_update.php", function(data) { $("#rect_comments_text").append(data);} );
}, 3000);
Code:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$time_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$timestamp = time();
$last_time_query = "SELECT alias FROM $time_table";
$last_time_result = mysqli_query($connection,$last_time_query);
$last_time_rows = mysqli_fetch_array($last_time_result);
if ($last_time_rows['alias'] === $alias)
{
$last_time = $last_time_rows['time'];
$query = "SELECT * FROM $table WHERE time > $last_time ORDER BY text_id ASC"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
//APPEND NEW MESSAGES
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
}
//UPDATE LAST SYNC TIME
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
echo '<p> HERE </p>';
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','0')";
mysqli_query($connection,$update_query);
}
?>
You try this
$sql_update = "UPDATE time_table SET time= '$timestamp' WHERE alias = '$alias'";
if ($con->query($sql_update ) === TRUE) {
}
else{
echo "Error: " . $sql_update . "<br>" . $con->error;
}
You need to only check mysqli_num_rows to whether to insert or update data. You have to add ' around $alias in select query also. change your code as below:
//EITHER UPDATE THE EXISTING VALUE OR CREATE ONE FOR FIRST TIME VISITORS...
$last_time_query = "SELECT * FROM $time_table WHERE alias = '$alias'"; //change here add '
$last_time_result = mysqli_query($connection,$last_time_query);
if (mysqli_num_rows($last_time_result) == 0) //Only check number of rows
{
$update_query = "INSERT INTO $time_table (alias, time) VALUES('$alias','$timestamp')";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "UPDATE $time_table SET time = '$timestamp' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
So i have a table with a row, click on 'bearbeiten', i get to a formula where i can fill in the changed name or whatever, and then everything changes instead of only the fields i wrote something in and the rest stays.
So if i would only change name and click on save, every other field in the table goes blank.
I tried it with WHERE already, and read that POST is a good method but i think i can change it with making a few changes in the $sql statement, just don't know what.
<?php
//if(isset($...)
if($_GET['aktion'] == "speichern")
{
$ID = $_GET['ID'];
$Anrede = $_GET['Anrede'];
$Nachname = $_GET['Nachname'];
$Vorname = $_GET['Vorname'];
$Geburtsdatum = $_GET['Geburtsdatum'];
$Telefonnummer = $_GET['Telefonnummer'];
$Email = $_GET['Email'];
$sql = "UPDATE Adressbuch SET Anrede = '$Anrede', Nachname = '$Nachname',Vorname = '$Vorname', Geburtsdatum = '$Geburtsdatum', Telefonnummer = '$Telefonnummer', Email = '$Email' ORDER BY ID DESC LIMIT 1";
echo 'Zurueck zum Adressbuch<br>';
require_once ('konfiguration.php');
$db_erg = mysqli_query($db_con, $sql)
or die("Anfrage fehlgeschlagen: " . mysqli_error($db_con));
exit;
}
How about:
Just update the column, if you variable is not blank, else update it with the same value as the record already has.
UPDATE Adressbuch
SET Anrede = CASE WHEN '$Anrede' != '' THEN '$Anrede' ELSE Anrede END
,Nachname = CASE WHEN '$Nachname' != '' THEN '$Nachname' ELSE Nachname END
,Vorname = CASE WHEN '$Vorname' != '' THEN '$Vorname' ELSE Vorname END
,Geburtsdatum = CASE WHEN '$Geburtsdatum' != '' THEN '$Geburtsdatum' ELSE Geburtsdatum END
,Telefonnummer = CASE WHEN '$Telefonnummer' != '' THEN '$Telefonnummer' ELSE Telefonnummer END
,Email = CASE WHEN '$Email' != '' THEN '$Email' ELSE Email END
ORDER BY ID DESC LIMIT 1
Use as and see if it works. Thanks.
<?php
require_once ('konfiguration.php');
//if(isset($...)
if($_GET['aktion'] == "speichern")
{
$ID = $_GET['ID'];
$Anrede = $_GET['Anrede'];
$Nachname = $_GET['Nachname'];
$Vorname = $_GET['Vorname'];
$Geburtsdatum = $_GET['Geburtsdatum'];
$Telefonnummer = $_GET['Telefonnummer'];
$Email = $_GET['Email'];
//use where in your query to update the particular row
//in below query id = your column in database table
$sql = "UPDATE Adressbuch SET Anrede = '$Anrede', Nachname = '$Nachname',Vorname = '$Vorname', Geburtsdatum = '$Geburtsdatum', Telefonnummer = '$Telefonnummer', Email = '$Email' WHERE id='$ID'";
$db_erg = mysqli_query($db_con, $sql) or die("Anfrage fehlgeschlagen: " . mysqli_error($db_con));
echo 'Zurueck zum Adressbuch<br>';
exit;
}
?>
Use POST method instead of GET.