Let's say i have and array like this
$array= Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
Keys from this array are name of columns in table and values are value of columns which i need to update.
I want to update the table based on keys and values.
I am using ADODB
Please help me
try this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
$sql .= $key . " = " . $value . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
and of course the WHERE clause:
$sql .= " WHERE condition = value";
you will get the string:
UPDATE table SET id = 3, name = NAME, age = 12 WHERE condition = value
L.E: You might need to add apostrophes to strings so I have to change my code to something like this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= " WHERE condition = value";
which will produce this:
UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE condition = value
L.E 2: If you want the id column in your condition, the code becomes this:
$sql = "UPDATE table SET ";
foreach($array as $key=>$value) {
if($key == 'id'){
$sql_condition = " WHERE " . $key . " = " . $value;
continue;
}
if(is_numeric($value))
$sql .= $key . " = " . $value . ", ";
else
$sql .= $key . " = " . "'" . $value . "'" . ", ";
}
$sql = trim($sql, ' '); // first trim last space
$sql = trim($sql, ','); // then trim trailing and prefixing commas
$sql .= $sql_condition;
which will produce this result:
UPDATE table SET name = 'NAME', age = 12 WHERE id = 3
Hope this helps! :D
foreach ($update_array as $key => $testimonials) {
$name = mysql_real_escape_string($testimonials->name);
$content = mysql_real_escape_string($testimonials->content);
$id = intval($testimonials->id);
$sql = "UPDATE testimonials SET name='$name', content='$content' WHERE id=$id";
$result = mysql_query($sql);
if ($result === FALSE) {
die(mysql_error());
}
}
Source : https://stackoverflow.com/a/7884331/3793639
Other sources to check.
PHP SQL Update array and Simple UPDATE MySQl table from php array
You could use something like this for achieving that:
foreach($values as $value) {
if(!key_exists($value, $item)) {
return false;
}
$table->{$value} = $items[$value];
}
Assuming that the key index is always id and that adodb can use named placeholders you could do this:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$set = array();
$data = array();
while(list($key,$value)=each($array)) {
$data[':'.$key] = $value;
if($key!='id') {
$set[] = $key . ' = :' . $key;
// if no placeholders use $set[] = $key . " = '" . database_escape_function($value) . "'";
}
}
$sql = "UPDATE table SET ".implode($set, ',')." WHERE id=:id";
//$data is now Array(':id'=>'3', ':name'=>'NAME', ':age'=>'12');
//$sql is now "UPDATE table SET name=:name, age=:age WHERE id=:id";
$stmt = $DB->Prepare($sql);
$stmt = $DB->Execute($stmt, $data);
This is probably the shortest and easiest for you, you can also use something like this to achieve it:
$array = Array('id'=>'3', 'name'=>'NAME', 'age'=>'12');
$sql = "UPDATE table SET ";
$sql .= implode(', ', array_map(function($key, $value){
return is_numeric($value) ? "{$key} = {$value}" : "{$key} = '". mysql_real_escape_string($value). "'";
}, array_keys($array), $array));
$sql .= " WHERE id = 123";
// Result : UPDATE table SET id = 3, name = 'NAME', age = 12 WHERE id = 123
Related
So I'm trying to have the user update this table, but if the field is left blank i'd like the data to be left alone, not change it to a blank field or null, any ideas?
<?
elseif ($Code == "U")
{
$sql = "UPDATE movieDATA SET Name = '$Name', Genre = '$Genre', Starring = '$Starring', Year = '$Year', BoxOffice = '$BoxOffice' where IDNO = '$idno'";
$result= mysqli_query($link,$sql) or die(mysqli_error($link));
$showresult = mysqli_query($link,"SELECT * from movieDATA") or die("Invalid query: " . mysqli_error($link));
while ($row = mysqli_fetch_array($showresult))
{
echo ("<br> ID = ". $row["IDNO"] . "<br> NAME = " . $row["Name"] . "<br>");
echo("Genre = " . $row["Genre"] . "<br> Starring = " . $row["Starring"] . "<br>");
echo("Year = " . $row["Year"] . "<br> Box Office = " . $row["BoxOffice"] . "<br>");
}
}
?>
$fields = array(); // Take a blank array of fields and values.
$Name = trim($Name); // Trim the variable, user may add only spaces
$Genre = trim($Genre); // Do this for all variables.
$Starring = trim($Starring);
$Year = trim($Year);
$BoxOffice = trim($BoxOffice);
if (! empty($Name)) { // If user has filled the field, append to array.
$fields[] = "Name = '$Name'";
}
if (! empty($Genre)) {
$fields[] = "Name = '$Genre'";
}
if (! empty($Starring)) {
$fields[] = "Name = '$Starring'";
}
if (! empty($Year)) {
$fields[] = "Name = '$Year'";
}
if (! empty($BoxOffice)) {
$fields[] = "Name = '$BoxOffice'";
}
if (! empty($fields)) { // If the array is not empty, go for Query.
$sql = "UPDATE movieDATA SET "; // If user has not added any field value,
$sql .= implode(', ', $fields); // no SQL Query will be fired.
$sql .= " WHERE IDNO = '$idno'";
}
Your requirement:
Not to update the fields which user has left blank.
Solution:
Add if condition to check if every field is filled up.
One way to do this:
$q_set = [];
if (!empty($Name)) {
$q_set []= "Name = '$Name'";
}
if (!empty($Genre)) {
$q_set []= "Genre = '$Genre'";
}
/* ... */
if (!empty($q_set)) {
$sql = "UPDATE movieDATA SET " . implode(',', $q_set)
. " WHERE IDNO = '$idno'";
}
Note, that the variables passed into SQL should be escaped
When I try to update a table with the following query string using PHP:
UPDATE card_designs SET `card_price` = '6180',
`annual` = '257.3',
`initial_payment` = '6512.3'
WHERE card_id = '1'
It does not update correctly. card_price value is put in correctly. However annual comes in as 0 and initial_payment comes in as 6255.00.
It doesn't matter if the fields are a VARCHAR, DECIMAL, or DOUBLE. If the value has a decimal it's all messed up.
Also, if I run the above query in a SQL client, the query works fine.
Here is the PHP code that constructs the query. I'm using mysqli:
$sql = "UPDATE ". $table ." SET ";
$updates = array();
foreach ($variables as $field => $value) {
array_push($updates, "`$field` = '$value'");
}
$sql .= implode(', ', $updates);
//Add the $where clauses as needed
if (!empty($where)) {
foreach ($where as $field => $value) {
$value = $value;
$clause[] = "$field = '$value'";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
}
if (!empty( $limit)) {
$sql .= ' LIMIT '. $limit;
}
$query = $this->mysqli->query($sql);
I assume your database table fields datatype is Decimal(9,2)
// Prepare query
$table = "card_designs";
$variables = array(
"card_price" => "6180.00",
"annual" => "257.3",
"initial_payment" => "6512.3"
);
$where = array(
"id" => "1"
);
$sql = "UPDATE ". $table ." SET ";
$updates = array();
foreach ($variables as $field => $value)
{
array_push($updates, "$field = $value");
}
$sql .= implode(', ', $updates);
//Add the $where clauses as needed
if (!empty($where))
{
foreach ($where as $field => $value)
{
$value = $value;
$clause[] = "$field = $value";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
}
if (!empty( $limit))
{
$sql .= ' LIMIT '. $limit;
}
// Run query
if ($mysqli->query($sql))
{
echo "Record updated successfully";
}
My UPDATE query is updating jobResponsibilities field in table_2 just insert jobResponsibilities = c00017 but i want to insert all values like jobResponsibilities = C00001,C00302,C00303,C00287,C00286,C00285,C00017 not only jobResponsibilities = C00017
in one record.
My code is as follows:
function mySQLSafe( $value, $quote = "'"){
// strip quotes if already in
$value = get_magic_quotes_gpc() ? stripslashes($value) : $value;
$value = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($value) : mysql_escape_string($value);
// Stripslashes
if (get_magic_quotes_gpc()){
$value = stripslashes($value);
}
// Quote value
if (version_compare(phpversion(), "4.3.0") == "-1") {
$value = mysql_escape_string($value);
} else{
$value = mysql_real_escape_string($value);
}
$value = $quote . $value . $quote;
return $value;
}
$comcode = "SELECT jobCode, compCode
FROM first_table";
$comcode_RS = mysql_query($comcode, $timespace) or die (mysql_error());
while($row_comcode_RS = mysql_fetch_assoc($comcode_RS))
{
$jobCode = $row_comcode_RS['jobCode']; // more than one record
$compCode = $row_comcode_RS['compCode']; // more than one record
echo $updateSQL = "UPDATE second_table SET jobResponsibilities=".mySQLSafe($compCode)." WHERE jobCode=".mySQLSafe($jobCode)."";
$Result1 = mysql_query($updateSQL, $timespace) or die(mysql_error());
}
Use CONCAT to append the new value to the end of the column.
$updateSQL = "UPDATE second_table
SET jobResponsibilities = IF(jobResponsibilities = '', " .
mSQLSafe($compCode) . ",
CONCAT(jobResponsibilities, ',', " . mSQLSafe($compCode) . "))
WHERE jobCode=".mySQLSafe($jobCode);
However, this is poor schema design. Columns with comma-separated lists make many database operations difficult. You should use a separate table for job responsibilities, with rows for each combination of jobCode and compCode.
I have this function
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$arr = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
$set = "";
foreach($arr as $key => $v) {
$val = is_numeric($v) ? $v : "'" . $v . "'";
$set .= $key . '=' . $val . ', ';
}
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $set, $_POST['id']);
mysql_query($sql);
if ($carry == 'yes') {
redirect($carryUrl.'?id='.$_REQUEST['id']);
} else { echo "Done!"; }
echo $sql;
}
It outputs for example: UPDATE projects SET project_name='123', project_bold='123', project_content='123', WHERE id='12'
The last comma before where is preventing it from working. Is there a way of avoiding this? Im aware of the function implode, however I am not sure how to employ it in this situation.
Yes,
$sql = substr($sql,'',-1);
I would use
$sql = rtrim($sql, ',');
Either that or instead of appending to a string, append to an array and use implode.
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$array = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
foreach ($array as $key => $value) {
$value = mysql_real_escape_string($value); // this is dedicated to #Jon
$value = "'$value'";
$updates[] = "$key = $value";
}
$implodeArray = implode(', ', $updates);
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);
mysql_query($sql);
i'm trying to insert multiple data using a query, i've tried the implode function, the while loop, for loop, but still can't be done..
can u help plz
well i've a combobox box for selecting course name, created a function to get its ID and assign a variable. supose i'm a manager of a department and need to assign all staff below me a course, i select the course, input the date assigned and expected ending date. i've created another field in database to enter the training owner. Since i'm the 1 assigning the course, my name will appear as owner field.
$m_name = $_SESSION['SESS_FIRST_NAME'];
//combobox to get the department ID using variable $dept
//query to get all user concerning the department
$query = mysql_query("select userid from dept_user where dept_id=$dept LIMIT 0, 30 ");
$row= mysql_query($query);
//from here i'm not being able to execute
$qry = mysql_query("INSERT INTO course_detail(userid, course_id, date_assign, expected_end_date, owner) VALUES('$query','$name','$sdate', '$edate', '$m_name')" ) ;
$qry = mysql_query("INSERT INTO course_detail(userid, course_id, date_assign, expected_end_date, owner) VALUES('$query','$name','$sdate', '$edate', '$m_name')" ) ;
So, you're basically trying to insert $query in the userid column. In your code, $query is the result of a mysql select statement, thus a multi-array of user ids. Think of it like a simple SQL query, you can't execute that. Even more, you're doing mysql_query on a mysql_query result, which is plain wrong. Where does the $dept variable come from? What about the others? If you're sure they're valid here's what you need:
// Get the user ids you need to insert in the db
$query = "select userid from dept_user where dept_id=$dept LIMIT 0, 30 "; // this will select the first 30 users in a dept
$buffer = mysql_query($query); // this is a variable that will hold all the results returned by the query above
// While we still have results in the $buffer array, fetch those in the $data array
while ($data = mysql_fetch_assoc($buffer)) {
$insert_query = "INSERT INTO course_detail(userid, course_id, date_assign, expected_end_date, owner) VALUES('".$data['userid']."','$name','$sdate', '$edate', '$m_name')"; // add the userid from the first query and the other data (don't know where you got those
$insert_buffer = mysql_query($insert_query); // execute the statement above, watch out so you don't overwrite the initial $buffer variable
}
// At this point you should have all the data in database
Also, I'm not sure you got the insert statement right
userid > $data['userid'] (ok)
course_id > $name (?!)
date_assign > $sdate (you sure?)
expected_end_date > $edate (ok)
owner > $m_name (ok?)
Make sure you have a good naming convention or else you get lost very easy.
Good luck, a lot of mistakes on just 5 lines of code.
Let's give it a wild guess and assume that this is what you want:
//query to get all user concerning the department
$query = mysql_query("
SELECT userid
FROM dept_user
WHERE dept_id=$dept
");
if(mysql_num_rows($query)){
$insertSQL = "
INSERT INTO course_detail
(userid, course_id, date_assign, expected_end_date, owner)
VALUES
";
$rowsSQL = Array();
while($row = mysql_fetch_row($query)){
$rowsSQL[] = "('{$row['userid']}','$name','$sdate', '$edate', '$m_name')";
}
mysql_query($insertSQL.implode(',', $rowsSQL));
}
Also you should start reading the manual.
Read the doc, you can separate each set of data with a comma.
$values = array();
$values[] = array(
'id' => 1,
'v1' => 'a',
'v2' => 'b'
);
$values[] = array(
'id' => 2,
'v1' => 'c',
'v2' => 'd'
);
$sql = "INSERT INTO course_details (id,v1,v2) VALUES ";
foreach ($values as $value) {
$sql .= '('.$value['id'].','.$value['v1'].','.$value['v2'].'),';
}
$sql = substr ($sql,0,-1) // that will remove the last comma
mysql_query($sql);
Below is the function and here is how to use it
Update Query
$data_array=array(
"bannername" => addslashes($_POST["bannername"]),
"url" => $_POST["url"],
"openin" => $_POST["openin"]
);
$param=" bannerid = '$bannerid'";
$sql=db_makequery("banner",$data_array,"update",$param);
Insert Query
$data_array=array(
"bannername" => addslashes($_POST["bannername"]),
"url" => $_POST["url"],
"openin" => $_POST["openin"]
);
$sql=db_makequery("banner",$data_array);
Function
function db_makequery($table, $data, $action = 'insert', $parameters = '')
{
reset($data);
if ($action == 'insert')
{
$query = 'insert into ' . $table . ' (';
while (list($columns, ) = each($data)) {
$query .= $columns . ', ';
}
$query = substr($query, 0, -2) . ') values (';
reset($data);
while (list(, $value) = each($data))
{
switch ((string)$value)
{
case 'now()':
$query .= 'now(), ';
break;
case 'null':
$query .= 'null, ';
break;
default:
//$query .= '\'' . tep_db_input($value) . '\', ';
$query .= '\'' . $value . '\', ';
break;
}
}
$query = substr($query, 0, -2) . ')';
}
elseif ($action == 'update')
{
$query = 'update ' . $table . ' set ';
while (list($columns, $value) = each($data))
{
switch ((string)$value) {
case 'now()':
$query .= $columns . ' = now(), ';
break;
case 'null':
$query .= $columns .= ' = null, ';
break;
default:
//$query .= $columns . ' = \'' . tep_db_input($value) . '\', ';
$query .= $columns . ' = \'' . $value . '\', ';
break;
}
}
$query = substr($query, 0, -2) . ' where ' . $parameters;
}
return $query;
}