How to update data in SQL table without overwritting existing data - php

How can I update a value that already exists in SQL database table without overwriting existing data in the table.
Here is a code I have tried
public function updateSch()
{
// $query = "UPDATE tbl_school_data SET schoolA = ? WHERE schoolId = ?";
$query = "UPDATE tbl_school_data SET schoolA = schoolA & ? WHERE schoolId = ?";
$obj = $this->conn->prepare($query);
$this->schoolA = htmlspecialchars(strip_tags($this->schoolA));
$this->schoolId = htmlspecialchars(strip_tags($this->schoolId));
$obj->bind_param("ss", $this->schoolA, $this->schoolId);
if ($obj->execute()) {
return true;
}
return false;
}
but when I run this the data changes to 0 for reasons I really don't understand I have tried with the query commented out it but that just does the regular update i.e. overwrite existing data but I would really like to know how to add to the data without overwriting.

You can use concat
UPDATE tbl_school_data SET schoolA = concat(ifnull(schoolA,''),?) WHERE schoolId = ?

When the data changes to 0, it is usually an indication that your structure has the data value type set as INT. If you try to input text (or any invalid formats, as a matter of fact), the value will set itself to 0.

Related

mySQL: UPDATE statement for 2 tables with a foreign key relation

I have created 2 tables with the following structure:
mitarbeiter
==================
maID (PK, AUTO_INCREMENT, NOT NULL)
maAnrede
maName
maVname
maDurchwahl
maEmail
maMobilfunkNr
maKartenanzahl
maFirma
mobilfunkkarten
==============================
mfkID (PK, AUTO_INCREMENT, NOT NULL)
mfkTarif
mfkStatus
mfkKartennr
mfkPin
mfkSuperpin
maID(FK)
Now I would like the web user to type in values into form fields. (I will let him edit his/her entries there, which will be saved in the mysql-database. So these entries are NOT new!) After clicking the "Save"-Button, the data will be saved into the corresponding 2 tables. My mySQL-Query looks like this (I am using symfony's php templating engine "twig"):
DatabaseLink::getInstance()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["btnSaveMfk"]))
{
$stmt = DatabaseLink::getInstance()->prepare("UPDATE mitarbeiter SET
maAnrede = :maAnrede,
maVname = :maVname,
maName = :maName,
maMobilfunkNr = :maMobilfunkNr,
maKartenanzahl = :maKartenanzahl,
maEmail = :maEmail,
maFirma = :maFirma
WHERE mitarbeiter.maID = :maid;
UPDATE mobilfunkkarten SET mfkTarif = :mfkTarif,
mfkStatus = :mfkStatus,
mfkPin = :mfkPin,
mfkSuperpin = :mfkSuperpin");
$status = $stmt->execute(array(
":maid" => $_POST["txtMaId"],
":maAnrede" => $_POST["txtAnrede"],
..................,
..................,
..................
));
header("Location: Mobilfunkdaten"); //back to the PHP table that shows all entries
}
I believe that this won't work because the 2 tables are related with a foreign key and if I update both tables without this relation, the statement will result in an error or it will overwrite something unrelated. Am I right with this assumption?
Any solutions on how to solve this? I just can't think of any way on how to make sure that anything the user types into the form fields will be saved as 1 dataset into these 2 tables, i.e. the UPDATED data in the child table 'mobilfunkkarten' will be related to the Primary Key Number in the parent table 'mitarbeiter'.
mitarbeiter = workers mobilfunkkarten = mobile phone cards (SIM cards)
With update statements, the auto_increment value doesn't change. And, as I can see from your query, you're not updating the maID value, so it gives no reason for the MySQL parser to throw an error. Your query is correct, as far as I can see.
Just one small thing. Define the keys of the associative array without the : symbol. You use this symbol to indicate that this place is reserved for the value stored in the variable by the following name. For example, using
$stmt = DatabaseLink::getInstance()->prepare("update table_name set name=:name where id=:id");
$status = $stmt->execute(array("name" => "test", "id" => 2));
indicates to the parser that the name corresponding to ID 2 has to be updated to test.
But, you are already using the : along with the name of the key. So, in your example, your query looks for the value in a key called maAnrede in your script, but the key that you have defined is :maAnrede, and hence, the query doesn't work as expected.
Try this change. It'll surely work.
DatabaseLink::getInstance()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["btnSaveMfk"]))
{
$stmt = DatabaseLink::getInstance()->prepare("UPDATE mitarbeiter SET
maAnrede = :maAnrede,
maVname = :maVname,
maName = :maName,
maMobilfunkNr = :maMobilfunkNr,
maKartenanzahl = :maKartenanzahl,
maEmail = :maEmail,
maFirma = :maFirma
WHERE mitarbeiter.maID = :maid;
UPDATE mobilfunkkarten SET mfkTarif = :mfkTarif,
mfkStatus = :mfkStatus,
mfkPin = :mfkPin,
mfkSuperpin = :mfkSuperpin");
$status = $stmt->execute(array(
"maid" => $_POST["txtMaId"],
"maAnrede" => $_POST["txtAnrede"],
..................,
..................,
..................
));
header("Location: Mobilfunkdaten"); //back to the PHP table that shows all entries
}
This situation happened with me as well, and this is the solution that worked for me!
I believe I fixed it. You need to add this line in the second SQL statement:
WHERE mobilfunkkarten.maID = :maid");
See below where I included it.
Fixed the issue for me but I am not entirely sure how safe this one is...any criticism on this approach? Other suggestions?
DatabaseLink::getInstance()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["btnSaveMfk"]))
{
$stmt = DatabaseLink::getInstance()->prepare("UPDATE mitarbeiter SET
maAnrede = :maAnrede,
maVname = :maVname,
maName = :maName,
maMobilfunkNr = :maMobilfunkNr,
maKartenanzahl = :maKartenanzahl,
maEmail = :maEmail,
maFirma = :maFirma
WHERE mitarbeiter.maID = :maid;
UPDATE mobilfunkkarten SET mfkTarif = :mfkTarif,
mfkStatus = :mfkStatus,
mfkPin = :mfkPin,
mfkSuperpin = :mfkSuperpin
WHERE mobilfunkkarten.maID = :maid");
$status = $stmt->execute(array(
"maid" => $_POST["txtMaId"],
"maAnrede" => $_POST["txtAnrede"],
..................,
..................,
..................
));
header("Location: Mobilfunkdaten"); //back to the PHP table that shows all entries
}

SQL UPDATE value as null or string

I searched almost whole internet, but could not find something similar, yet my question looks so simple.
I have a php code like so:
$id = 1;
if (!isset($_POST['port1'])) {
$port1 = null;
}
... which simply checks if submitted value is empty or not, if it is empty, then variable $port1 = null;
then, further in the code, I need to insert this value/update it in the database
$sql_update = ("UPDATE names_10 SET `digName1`=$port1 WHERE `device_id`='$id'");
...which should set the "digname1" to null. but it won't!
I tried every combination, every type of quotes, but every time I got UPDATE error..
any ideas?
Try this:
$id = 1;
if (!isset($_POST['port1'])) {
$port1 = "NULL";
}
$sql_update = ("UPDATE names_10 SET `digName1`= $port1 WHERE `device_id`='$id'");
I would rather suggest you to use PDO when you plan to bind something like this. There are a lot of benefits using PDO that would amaze you!

How to set a value in mysql to NULL using a variable?

I'm trying to set a variable to NULL if it's empty (after a form input) and update my db with it, but it keeps putting 0 in the field insted of NULL. (field is set to integer/NULL) I also tried $eloleg = "NULL" but that didn't work either.
if (!empty($_POST["eloleg"])) {
$eloleg = mysql_real_escape_string($_POST["eloleg"]);
}
else {
$eloleg = NULL;
}
mysqli_query($connection, "UPDATE $table SET eloleg='$eloleg' WHERE date='$eredeti_date'");
I think you wanted to do this:
$eloleg = 'NULL';
mysqli_query($connection, "UPDATE $table SET eloleg=$eloleg WHERE date='$eredeti_date'");
But as others have said, you should use a parametrized API to build your query, to avoid SQL injection as well as formatting pitfalls.

Updating MySQL DB with PHP

I'm using foreach to loop an array and update a MySQL database.
This is my code
foreach($result['getHiscore'] as $highScoreType => $highScoreValues){
$rank = $highScoreValues['rank'];
$lvl = $highScoreValues['lvl'];
$totalXp = $highScoreValues['totalxp'];
mysqli_query($con,"UPDATE Users SET Level("$highScoreType") = $lvl, Xp("$highScoreType") = $totalXp,
WHERE UserID= '1'");
}
i'm trying to conflate the word "level" with the contents of $highScoreType, the column titles in my DB are Leveloverall, Xpoverall, Levelattack, Xpattack and so on so i was planning on keeping the Level/Xp title constant and just changing the key.
This looks fine to me and when i tested the sql with pre-set values it updated fine, however using the variables doesn't update at all. I know that the variables are coming out of the array correctly as when i echo them inline with the foreach they print out in the correct format and order.
Is it my formatting thats the issue or am i doing missing something else?
If you echo the generated SQL query that should help you see any problems in the query.
It looks odd to me: UPDATE Users SET Level("$highScoreType") = $lvl
Shouldn't that just be UPDATE Users SET $highScoreType = $lvl ?
Be aware also that this sort of code is vulnerably to SQL injection attacks so always be wary of what could be in those variables.
To print the query do:
$query = "UPDATE Users SET Level("$highScoreType") = $lvl, Xp("$highScoreType") = $totalXp, WHERE UserID= '1'"
echo $query
mysqli_query($con, $query)

PHP & MS SQL: sp_helpconstraint <tablename> will not allow me to advance to the second data set with mssql_next_result()...?

I am trying to get the full definition for constraints on a particular table in MSSQL via PHP's mssql.dll driver, and when I call next_result() on the returned resource from the original query "sp_helpconstraint ", I either get an empty result set, or it does not advance to the next table of data...
IS there a direct query to the sys. tables that I can make that will pull the equivalent information without the extra data set?
This same problem seems to exist with the SQL SERVER ddl supplied by MS as well.
Code is as follows:
$sql = '/* Getting '.$this->ExpectedTableVO->GetTableName().' Constraints */ sp_helpconstraint \''.$this->ExpectedTableVO->GetSchema().'.'.$this->ExpectedTableVO->GetTableName().'\'';
$r = $this->db->Query($sql);
$results['Constraints'] = array();
$r = $this->db->NextResult($r);
while ($row = $this->db->FetchObj($r))
{
$results['Constraints'][] = $row;
}
This results in an empty set, despite there being plenty of constraints on the table in question. Without NextResult, I get the Table with a single row and column "Object Name" with the table name...
Otherwise an empty set... WTF?!
I messed up...
Notice I overwrite $r with the nextresult() command... just calling that without overwriting it fixes this problem.
$sql = '/* Getting '.$this->ExpectedTableVO->GetTableName().' Constraints */ sp_helpconstraint \''.$this->ExpectedTableVO->GetSchema().'.'.$this->ExpectedTableVO->GetTableName().'\'';
$r = $this->db->Query($sql);
$results['Constraints'] = array();
$r = $this->db->NextResult($r);
//above line should be just "$this->db->NextResult($r);"
while ($row = $this->db->FetchObj($r))
{
$results['Constraints'][] = $row;
}

Categories