How do I update multiple columns in MySQL with PhP? - php

I want my form to update values in my MySQL database, how would I go on doing that with multiple values ? I think I understand how it works with single values, but not with multiple. Any help is appreciated, this is how far I got:
$queue = "UPDATE hurlumhei SET (barn, voksenuke, voksenhelg, klippekort, klippekortmega, parkering) VALUES ($barn, $voksenuke, $voksenhelg, $klippekort, $klippekortmega, $parkering)";

Like this:
UPDATE hurlumhei
SET barn = $barn
,voksenuke = $voksenuke
,voksenhelg = $voksenhelg
,klippekort = $klippekort
,klippekortmega = $klippekortmega
,parkering = $parkering
Since you are using PHP, you probably want to look into prepared statements to send in values.

Related

Update cell value by adding a string to current value with SQL and PHP

Hello dear Developers,
I am trying to add a string value to a specific cell on my SQL database but its not working somehow, I have tried with CONTACT but its updating all cells, even if I have added WHERE conditions.
Here is the code I am using:
$asset = "Neo";
$space = " "
$sql="UPDATE `open_trades` SET `asset` = '$asset $space;', `laverage` = '$laverage', `live_price` = '$live_price' WHERE `id` = '$trade_id';";
I need $asset and $space combined, in this case Neo  but I am not sure how to implement it, on this way its updating the cell but its adding only $space, and the cell value its updating to only $space.
I also tried to combine values via PHP but still adding only $space.
Thanks and regards.

Proper way to manipulate database

My entry form I have an inventory database with tables like aluminium, iron etc... Each table contains a subcategory of items like aluminium_pala, iron_1.5inch and so on. The entry code is like this:
include("dbConnect.php");
$orderNo = $_POST["number"];
if(isset($_POST["mat1"])&&$_POST["mat1"]!=NULL)
{
$mat1 = $_POST["mat1"];
$selmat1 = $_POST["selmat1"];
$amtmat1 = $_POST["amtmat1"];
$query = "INSERT INTO $mat1 ($selmat1,orderNo) VALUES (-$amtmat1,$orderNo);";
if(!($result = $mysqli->query($query)))
print "<div class='error'>insertion failed. Check your data</div>";
}
if(isset($_POST["mat2"])&&$_POST["mat2"]!=NULL)
{
$mat2 = $_POST["mat2"];
$selmat2 = $_POST["selmat2"];
$amtmat2 = $_POST["amtmat2"];
$query = "INSERT INTO $mat2 ($selmat2,orderNo) VALUES (-$amtmat1,$orderNo);";
if(!($result = $mysqli->query($query)))
print "<div class='error'>insertion failed. Check your data</div>";
}... and it goes on till mat11
I am trying to collect each similar table (mat1, mat2..) and their corresponding item (selmat1, selmat2...) and bunch the all in one query. That is, instead of going
INSERT INTO al_openable (zPala,orderNo) VALUES (23,14);
INSERT INTO al_openable (outer,orderNo) VALUES (50,14);
I am trying to execute it like
INSERT INTO al_openable (zPala,outer,orderNo) VALUES (23,50,14);
I need this to avoid duplicate foreign key entry(for $orderNo). One idea I've been considering is to use UPDATE if the order number is pre-existing. Do you guys think this is a good idea? And if so, what will be the best way to execute it? If not, how would a more experienced programmer solve this conundrum?
I think this question is related to your query: Multiple Updates in MySQL
You may use ON DUPLICATE KEY UPDATE in combination with INSERT statement.

Insert multiple same named fields into MySQL Database using PHP

I have multiple fields with names that look like name_$i and I am trying to figure out a way to "on submit", send them all to the database. The thing is that the form is looped and the insert has to be able to adapt to the number of fields in the form. Is there a way to do this???
<?php
$fldcnt = $_POST['fldcnt'];
$i = $_POST['i'];
for ($i = 0; $i < $fldcnt; $i++){
$NAME = $_POST['name_$i'];
$AGE = $_POST['age_$i'];
$ADDRESS = $_POST['address_$i'];
$TELEPHONE = $_POST['telephone_$i'];
$EMAIL = $_POST['email_$i'];
$q_register_new_users = "insert into registration set
NAME = '$NAME',
AGE = '$AGE',
ADDRESS = '$ADDRESS',
TELEPHONE = '$TELEPHONE',
EMAIL = '$EMAIL'";
mysql_query($q_new_products,$connection) or die(mysql_error());
};
?>"
HTML and PHP
You can enter input fields into an array by simply calling the field name[]. Like so:
<input name="name[]" />
You can then use PHP to loop through the fields like so:
foreach($_POST['name'] as $key=>$value){
// Insert the value of the form field into a string or query
// i.e. build the query
$query .= $value;
}
// Then execute the query for each set of fields
The logic above is actually incorrect, but it should give you an idea of what I mean.
MySQL
Your SQL syntax is incorrect, the correct syntax for inserting into a MySQL database is:
INSERT INTO `table` (`field_1`, `field_2`)
VALUES ('value_1', 'value_2')
PLEASE NOTE
The use of the mysql_ functions is hugely discouraged due to there impending deprecation. Instead, most PHP programmers are now using the PDO / SQLite Classes. Whilst these might seem complex, they are actually pretty simple and offer a much more secure way of executing SQL statements.
PDO
SQLite
The syntax for INSERT statement should be like this,
INSERT INTO registration (NAME , AGE , ADDRESS, TELEPHONE, EMAIL)
VALUES ('$NAME', '$AGE', '$ADDRESS','$TELEPHONE', '$EMAIL')
but hte query above is vulnerable with SQL INJECTION, please read the article below to learn how to protect from it,
How can I prevent SQL injection in PHP?
If you are going to keep structure of your code, you need to use double quotes instead of apostrophes
$NAME = $_POST["name_$i"];
or put the variable out
$NAME = $_POST['name_'.$i];
Using array is best way to do this. But if you still want to go head with a counter then you could use
for($i = 0;isset($_POST["name_{$i}"]);$i++)
{
// name found
}
Please note that this code may not be optimal if the name_xx fields are coming from checkboxes, where a user selected items and skipped some in between.
PS. I posted this a comment but it is more suitable as an answer.

MySQL query not inserting data

I'm in a bit of a pickle here, its just that I'm trying to enter some data that I get from users into a table, but for some reason it won't let me insert the data, however I have exactly the same query for another part of the table and that seems to work perfectly fine.
for example when I execute this query, it doesn't work:
$updateibtask2 = "UPDATE ibtask_task2_75beep SET
Trial1_tone_actual= '$taskerror[0]', Trial2_tone_actual= '$taskerror[1]', Trial3_tone_actual= '$taskerror[3]',
Trial4_tone_actual= '$taskerror[4]', Trial5_tone_actual= '$taskerror[5]', Trial6_tone_actual= '$taskerror[6]',
Trial7_tone_actual= '$taskerror[7]', ... WHERE user_id = '$memberid'";
However, when I try this query it works perfectly fine:
$updateibtask2_estimate = "UPDATE ibtask_task2_75beep SET
Trial1_tone_estimate= '$taskerror[0]', Trial2_tone_estimate= '$taskerror[1]', Trial3_tone_estimate= '$taskerror[3]',
Trial4_tone_estimate= '$taskerror[4]', Trial5_tone_estimate= '$taskerror[5]', Trial6_tone_estimate= '$taskerror[6]',
Trial7_tone_estimate= '$taskerror[7]', ... WHERE user_id = '$memberid'";
I'm just wondering where I'm going wrong?
Also if it helps the PHP code that I'm using to run these queries are:
$task2 = array();
$task2 = $_SESSION['task2'];
$task2estimate = array();
$task2estimate = $_SESSION['estimatedpress2'];
$task2actual = array();
$task2actual = $_SESSION['actualpress2'];
addacutalerror_75($memberid, $task2actual);
addestimatederror_75($memberid, $task2estimate);
Also to check whether there was data present for $task2actual I had done an echo ..[0], .. [1].. etc and there was data present in the array.
Updated
For those who are searching for solutions and have the same problem, here's what I did:
function addacutalerror_75($memberid, $task2actual) {
$insertmember = "INSERT INTO ibtask_task2_75beep (user_id, Trial1_tone_actual,
Trial2_tone_actual, Trial3_tone_actual, Trial13_tone_actual,
Trial14_tone_actual, ..., Trial40_notone_actual) VALUES ('$memberid', '$task2actual[0]', '$task2actual[1]', '$task2actual[3]', '$task2actual[18]', '$task2actual[21]', '$task2actual[22]', '..., '$task2actual[24]', '$task2actual[29]', '$task2actual[33]','$task2actual[38]' )";
mysql_query($insertmember) or die(mysql_error());
}
by the way, UPDATE is very different from INSERT.
UPDATE - modify the existing record(s) on the table.
INSERT - adds new record(s) on the table.
Your query is fine but you are doing update. But you want to insert record not to update record right? The query when you insert record looks like this,
$updateibtask2 = "INSERT INTO ibtask_task2_75beep
(Trial1_tone_actual, Trial2_tone_actual,
Trial3_tone_actual,...)
VALUES ('$taskerror[0]', '$taskerror[1]',...)";
and your query is vulnerable with SQL Injection. Please take time to read the article below to protect against SQL injection,
Best way to prevent SQL injection in PHP?

Lots of 'If statement', or a redundant mysql query?

$url = mysql_real_escape_string($_POST['url']);
$shoutcast_url = mysql_real_escape_string($_POST['shoutcast_url']);
$site_name = mysql_real_escape_string($_POST['site_name']);
$site_subtitle = mysql_real_escape_string($_POST['site_subtitle']);
$email_suffix = mysql_real_escape_string($_POST['email_suffix']);
$logo_name = mysql_real_escape_string($_POST['logo_name']);
$twitter_username = mysql_real_escape_string($_POST['twitter_username']);
with all those options in a form, they are pre-filled in (by the database), however users can choose to change them, which updates the original database. Would it be better for me to update all the columns despite the chance that some of the rows have not been updated, or just do an if ($original_db_entry = $possible_new_entry) on each (which would be a query in itself)?
Thanks
I'd say it doesn't really matter either way - the size of the query you send to the server is hardly relevant here, and there is no "last updated" information for columns that would be updated unjustly, so...
By the way, what I like to do when working with such loads of data is create a temporary array.
$fields = array("url", "shoutcast_url", "site_name", "site_subtitle" , ....);
foreach ($fields as $field)
$$field = mysql_real_escape_string($_POST[$field]);
the only thing to be aware of here is that you have to be careful not to put variable names into $fields that would overwrite existing variables.
Update: Col. Shrapnel makes the correct and valid point that using variable variables is not a good practice. While I think it is perfectly acceptable to use variable variables within the scope of a function, it is indeed better not use them at all. The better way to sanitize all incoming fields and have them in a usable form would be:
$sanitized_data = array();
$fields = array("url", "shoutcast_url", "site_name", "site_subtitle" , ....);
foreach ($fields as $field)
$sanizited_data[$field] = mysql_real_escape_string($_POST[$field]);
this will leave you with an array you can work with:
$sanitized_data["url"] = ....
$sanitized_data["shoutcast_url"] = ....
Just run a single query that updates all columns:
UPDATE table SET col1='a', col2='b', col3='c' WHERE id = '5'
I would recommend that you execute the UPDATE with all column values. It'd be less costly than trying to confirm that the value is different than what's currently in the database. And that confirmation would be irrelevant anyway, because the values in the database could change instantly after you check them if someone else updates them.
If you issue an UPDATE against MySQL and the values are identical to values already in the database, the UPDATE will be a no-op. That is, MySQL reports zero rows affected.
MySQL knows not to do unnecessary work during an UPDATE.
If only one column changes, MySQL does need to do work. It only changes the columns that are different, but it still creates a new row version (assuming you're using InnoDB).
And of course there's some small amount of work necessary to actually send the UPDATE statement to the MySQL server so it can compare against the existing row. But typically this takes only hundredths of a millisecond on a modern server.
Yes, it's ok to update every field.
A simple function to produce SET statement:
function dbSet($fields) {
$set='';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
return substr($set, 0, -2);
}
and usage:
$fields = explode(" ","name surname lastname address zip fax phone");
$query = "UPDATE $table SET ".dbSet($fields)." WHERE id=$id";

Categories