With this query I update images fields in database:
$sql = $connection->prepare('UPDATE ads img1 = ?, img2 = ?, img3 = ? WHERE id = ?');
$sql->bind_param("ssss", $nameImg1, $nameImg2, $nameImg3, $id);
But this work fine if user update all 3 images, not only one or two. if user change just one image, for example change img2, img1 and img3 going to update to empty value because I use this condition:
$img1 = $_POST["img-1-val"];
$img2 = $_POST["img-2-val"];
$img3 = $_POST["img-3-val"];
if($img1 != 'NULL'){
$nameImg1 = $date.'_'.$adsid.'_1';
}
if($img2 != 'NULL'){
$nameImg2 = $date.'_'.$adsid.'_2';
}
if($img3 != 'NULL'){
$nameImg3 = $date.'_'.$adsid.'_3';
}
in html:
<input type="hidden" name="img-1-val" value="NULL"/>
<!-- this already has image -->
<input type="hidden" name="img-2-val"/>
<input type="hidden" name="img-3-val"/>
If each image has image, value is NULL if there is no image set, it is empty, if user change any image, it set base64 value.
But the main problem is, I don't want to update any img field in database if $_POST return NULL as value, already it update all fields, img1, img2, img3,and this cause of removing previously data. How can I update database field if value not equal to NULL?
Consider these codes run in edit page.
Also my problem is mysqli query not if condition.
You can make your update query dynamic like this :
/* function to build SQL UPDATE string */
function build_sql_update($table, $data, $where)
{
$cols = array();
foreach($data as $key=>$val) {
if($val != NULL) // check if value is not null then only add that colunm to array
{
$cols[] = "$key = '$val'";
}
}
$sql = "UPDATE $table SET " . implode(', ', $cols) . " WHERE $where";
return($sql);
}
In this way, only those columns will be updated which has valid values.
So, you have to just check with different variable with query.
This will check one by one image and if all the images have values then it will update all three images otherwise one by one.
This may help.
if((isset($img1)) && ($img1 != 'NULL')){
$nameImg1 = $date.'_'.$adsid.'_1';
$sql = $connection->prepare('UPDATE ads img1 = ? WHERE id = ?');
$sql->bind_param("ss", $nameImg1, $id);
}
if((isset($img2)) && ($img2 != 'NULL')){
$nameImg2 = $date.'_'.$adsid.'_2';
$sql = $connection->prepare('UPDATE ads img2 = ? WHERE id = ?');
$sql->bind_param("ss", $nameImg2, $id);
}
if((isset($img3)) && ($img3 != 'NULL')){
$nameImg3 = $date.'_'.$adsid.'_3';
$sql = $connection->prepare('UPDATE ads img3 = ? WHERE id = ?');
$sql->bind_param("ss", $nameImg3, $id);
}
Related
I am inserting data from JSON file using A API.
Now, the JSON file will send genres. Now, some JSON file will send 2 genres values, some JSON fie will send 100 values.
So, I don't know, how insert them.
See this code, this is a short version of my code. Currently, I have genres1 to genres100 numbers for each title in my original file. But here, i only shown genres1 to genres5, for the sake of simplicity.
So, as you can see, the code is very long, if i insert upto 100 genres value. How to make it short? Using Forloop or something?
<?php
$requestsDone = 1;
$maxRequests = 15;
while ($requestsDone <= $maxRequests) {
include 'logo/connectdb.php';
$requestsDone++;
$response = file_get_contents("https://api.themoviedb.org/3/movie/".($requestsDone-1)."?api_key=522cexxxxxxe0c834a");
if ($response != FALSE) {
$response = json_decode($response, true);
}
$firstname = "";
$lastname = "";
try {
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO TABLE (title, genres1,genres2,genres3,genres4,genres5)
VALUES (:title, :genres)");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':genres1', $genres1);
$stmt->bindParam(':genres2', $genres2);
$stmt->bindParam(':genres3', $genres3);
$stmt->bindParam(':genres4', $genres4);
$stmt->bindParam(':genres5', $genres5);
// insert a row
$title = $response["title"];
if ( isset($response["genres"][0]["name"]) != "" )
$genres1 = $response["genres"][0]["name"];
if ( isset($response["genres"][1]["name"]) != "" )
$genres2 = "".$response["genres"][1]["name"]."";
if ( isset($response["genres"][2]["name"]) != "" )
$genres3 = "".$response["genres"][2]["name"]."";
if ( isset($response["genres"][3]["name"]) != "" )
$genres4 = "".$response["genres"][3]["name"]."";
if ( isset($response["genres"][4]["name"]) != "" )
$genres5 = "".$response["genres"][4]["name"]."";
$stmt->execute();
echo "New records created successfully";
}
}
?>
Here's an example using 2 tables instead of 1.
Assume tables (Note: genre_id or the autoincremented id do not go in this table)
movie
-----
tmdb_id | movie_title | budget
genre
-----------
genre_id (autoincrement primary key) | movie_id(foreign key) | genre_title
Your PHP would look like:
<?php
$requestsDone = 1;
$maxRequests = 15;
while ($requestsDone <= $maxRequests) {
include 'logo/connectdb.php';
$requestsDone++;
$response = file_get_contents("https://api.themoviedb.org/3/movie/".($requestsDone-1)."?api_key=522cexxxxxxe0c834a");
if ($response != FALSE) {
$response = json_decode($response, true);
}
$firstname = "";
$lastname = "";
try {
$title = $response["title"];
$tmdb_id = $response["tbdb_id"]; //Or the correct name
$budget = $response["budget"];
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO movie (tmdb_id,movie_title,budget)
VALUES (:tmdbid,:title,:budget)");
$stmt->bindParam(':tmdbid', $title,PDO::PARAM_INT);
$stmt->bindParam(':title', $title,PDO::PARAM_STR);
$stmt->bindParam(':budget', $title,PDO::PARAM_INT);
// insert a row
$stmt->execute();
$stmt = $conn->prepare("INSERT INTO genre (movie_id,genre_title) VALUES (:genrefk,:title)");
$genre = "";
$stmt->bindParam(':genrefk', $tmdb_id,PDO::PARAM_INT);
$stmt->bindParam(':title', $genre);
if (isset($response["genres"]) && is_array($response["genres"])) {
foreach ($response["genres"] as $genreObject) {
$genre = $genreObject["name"];
$stmt->execute();
}
}
echo "New records created successfully";
}
}
?>
What this does is:
Inserts the movie information
Inserts between 0 to N movie genres which are in the result. Each genre is a new insert in another table.
To get all genres associated with a movie you'd do something like:
SELECT * FROM movie JOIN movie_genre ON movie_genre.movie_id=movie.id;
Note: I've assumed that you'd use an automatically incrementing identifier for this but you can realistically use an identifier that is provided by the API instead. In that case you just need to change the "thisId" and the first insert accordingly.
Right now the update only works if all textboxes are filled out, so the user can't just update productName for example. There isn't an error, but if the other textboxes are left blank then the database is updated with blanks and 0's. I want this to update whatever textboxes receive input, be it one or all, and leave the rest of the info alone if nothing is entered.
If productName for that row is Samsung, description is 'A phone' wholesalePrice is 179.99 and I just update the productName textbox only I still want the description and wholesalePrice to stay the same. Right now if I just update the productName only then the wholesalePrice shows as 0.00 and the description is blank. I tried using OR statements rather than commas in the query and whatever textbox I entered info in returned a 0.
if(isset($_POST['id'])) {
try {
$query = "UPDATE products SET productName = :productName, description = :description, wholesalePrice = :wholesalePrice,
retailPrice = :retailPrice, category = :category, quantityOnHand = :quantityOnHand
WHERE productID = :productID";
$statement = $db->prepare($query);
$statement->bindValue(':productID', $_POST['id']);
$statement->bindValue(':productName', $productName);
$statement->bindValue(':description', $description);
$statement->bindValue(':wholesalePrice', $wholesalePrice);
$statement->bindValue(':retailPrice', $retailPrice);
$statement->bindValue(':category', $category);
$statement->bindValue(':quantityOnHand', $quantityOnHand);
$statement->execute();
$statement->closeCursor();
//reload page after data is entered into the table and display a message if successful for 3 seconds before redirect
$page = $_SERVER['PHP_SELF'];
header('Location: ' . $_SERVER["HTTP_REFERER"] );
exit;
You can use a helper array for your columns to bind values dynamically if each $_POST value is set. Then you can create the update query for only those values.
$fields = array('productName', 'description', 'wholesalePrice', 'retailPrice', 'category', 'quantityOnHand');
$values = array();
$binds = array();
foreach($fields as $key => $value) {
if (isset($_POST[$value])) {
$values[] = $value.' = :'.$value;
$binds[':'.$value] = $_POST[$value];
}
}
if (!empty($values)) {
$query = "UPDATE products SET ";
$query .= implode(', ', $values);
$query .= " WHERE productID = :productID";
$binds[':productID'] = $_POST['id'];
$statement = $db->prepare($query);
$statement->execute($binds);
$statement->closeCursor();
}
EDIT:
If you have the values stored in variables then you can use variable variables:
foreach($fields as $key => $value) {
if (isset($$value)) {
$values[] = $value.' = :'.$value;
$binds[':'.$value] = $$value;
}
}
You need to pass all existing values to form fields so existing data is passed to the sql update if nothing changes. On submit validate the data, then do the update.
<textarea name="description">'.$row['description'].'</textarea>
if(isset($_POST['id'])) {
$productname = $_POST['productname'];
$description = $_POST['description'];
// etc ....
try {
// sql
}catch{
// error
}
}
I'm trying to update one row (= ID) of a mysql table from multiple form fields (text fields and text areas). The table looks like this:
ID | Col 1 | Col 2 | Col 3 ... | Col 50
Everything works fine, if I use $_Post[] variables like this
$Name = $_POST['Name'];
$Name2 = $_POST['Name2'];
$sql= "UPDATE Bilder SET Name = '$Name', Name2 = '$Name2' WHERE id = '$ID'";
<form id="InsertData" action="insert-dataset.php" method="post">
<input type="hidden" name="ID" id="ID" value="'.$row->id.'" />
<input type="text" name="Name" value="'.$row->Name.'" /><br />
<input type="text" name="Name2" value="'.$row->Name.'" /><br />
<input type="submit" name="submit" value="Daten eintragen" class="sendbutton" />
</form>
Since I have hundreds of fields I would rather use an array like so:
<input type="text" name="Name[]" value="'.$row->Name.'" />
I found working examples for updating all cells of one column. But I have to update all colums for one ID.
Any help would be appreciated. Thanks in advance!
This is the final result:
$col_result = mysql_query("SHOW COLUMNS FROM Bilder");
$row_result = mysql_query(sprintf("SELECT * FROM Bilder WHERE id = %s", $ID));
if(!$col_result) {
echo 'Konnte Anfrage nicht ausführen: ' . mysql_error();
exit;
}
if ( !empty($_POST) ) {
$aDataSet = array();
while( list( $field, $value ) = each( $_POST )) {
$aDataSet[] = $field . "='" . $value . "'";
}
$update_sql = "UPDATE Bilder SET " . implode( ',', $aDataSet );
$update_sql .= sprintf("WHERE id = '$ID'");
$result = mysql_query($update_sql, $connection);
if(!$result)
{
die('');
}
echo '';
}
mysql_close($connection)
?>
The update query will only include colums that have corresponding input field (input name = column name). Since I have hundreds of input fields, I can spread them over multiple pages using the same code for the update query.
Thank you all for your help.
Probably something like that:
$str = '';
$id = 0;
foreach($_POST['Name'] as $value)
{
$id ++;
$str .= ($str == '' ? '' : ', ').'Name'.$id.' = \''.addslashes($value).'\'';
}
$sql= "UPDATE Bilder SET ".$str." WHERE id = '$ID'";
Note: on this example, your sql fields are Name1, Name2, Name3...
Note2: you should always at least use an addslashes method when pasting a variable inside a sql query, to protect yourself from hackers.
Here is a couple ideas.
Name your fields something useful. Naming them garbage like Name1, Name2 etc is going to bite you on the ass later down the line. Also be nice to the next guy thats going to have to look at this.
If you have a bunch of Meaningful or Unmeaningful fieldnames and don't want to manually type them all out in your code, maybe use the SQL DESCRIBE (http://dev.mysql.com/doc/refman/5.0/en/explain.html) or SHOW COLUMNS command (http://php.net/manual/en/function.mysql-list-fields.php)
Note: untested
<?php
// Get all of the field names
$col_result = mysql_query("SHOW COLUMNS FROM Bilder");
// make sure we could get the colnames from mysql
if(!$col_result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
// Handle a POST
if(!empty($_POST)){
// start preparing the update statement
$update_sql = "UPDATE Bilder SET ";
if(mysql_num_rows($col_result) > 0) {
// make a key = value statement for each column in the table
while($colrow = mysql_fetch_assoc($col_result)) {
// prepare the key = value statement
$update_sql .= sprintf(" %s = %s, ", $colrow["Field"], mysql_real_escape_string($_POST[$colrow["Field"]]));
}
}
// BTW this is going to have a extra "," in it use substr to clear it
$update_sql = substr_replace($update_sql ,"", -2);
// finish off by limiting this statement to only one row
$update_sql .= sprintf(" WHERE id = %s", mysql_real_escape_string($_POST["id"]));
// ACTUALLY RUN THIS STATEMENT
}
if(!$row_result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
// prepare the sql to fetch the current row we are working on
$row_result = mysql_query(sprintf("SELECT * FROM Bilder WHERE id = %s", $id));
// Get the row item that you are currently working on
$row = mysql_fetch_row($row_result);
// output all the formfields for the above row
if(mysql_num_rows($col_result) > 0) {
// Go through all of the columns and output the colname from $colrow and the value from $row
while ($colrow = mysql_fetch_assoc($col_result)) {
// The HTML (don't be daunted by that variable-variable http://php.net/manual/en/language.variables.variable.php)
echo '<input type="text" name="' . $colrow["Field"] . '" value="' . $row->{$colrow["Field"]} . '" /><br />';
}
}
?>
lastly, you may be better served by an EAV style of DB where the number of fields for a row is variable. (a fair example with php and mysql: http://www.iwilldomybest.com/2008/08/php-mysql-tip-3/)
Ok, I used preg_replace. This is probably not best practices. The code looks like this and works just fine:
// Handle a POST
if(!empty($_POST)){
// start preparing the update statement
$update_sql = "UPDATE Bilder SET ";
if(mysql_num_rows($col_result) > 0) {
// make a key = value statement for each column in the table
while($colrow = mysql_fetch_assoc($col_result)) {
// prepare the key = value statement
$update_sql .= sprintf("%s = '%s',", $colrow["Field"], mysql_real_escape_string($_POST[$colrow["Field"]]));
}
}
// BTW this is going to have a extra "," in it use substr to clear it
// finish off by limiting this statement to only one row
$update_sql .= sprintf("WHERE id = '$ID'");
$update_sql = preg_replace("/,WHERE/", "WHERE", $update_sql);
There are, of course, security issues. I will fix that. However, this is not that important, since this application is for personal use only. It is not publicly accessible.
I'm pretty new at this kind of thing so I Don't know how safe or effiecnt this is, but it does work.
if ($_POST['Submit']=="Update"){
unset($_POST['Submit']);
$refid=$_POST['refid'];
unset($_POST['refid']);
$update=$_POST;
// Update DB with array
foreach ($update as $col => $val) {
$colsvals=$col."='".$val."'";
$mysql = mysqli_query($db, "UPDATE $tbl SET $colsvals WHERE id='$refid'")
or die('Database Connection Error ('.mysqli_errno($db).') '.mysqli_error($db). " on query: UPDATE $tbl SET $colsvals WHERE id='$refid'");
}
}
I start by cleaning out things I don't want to Updated.
Then I really had to take a sec to make sure I have the double/single quotes, equals, and dots right in the colsvals statment.
But for me The Magic came from realizing I could let the Foreach loop run a new query each time it etterates through the update array.
Whenever I execute an update-query, my whole table is updated. What do I have to do when I just want ONE value to be updated?
Here is my database structure:
ID || photo || sequence
1 || test.png || 1
2 || bla.png || 2
Whenever I execute this script,
if (isset($_POST['submitted'])) {
$project = new Project();
$project->sequence = $_POST['sequence'][$key];
$projectid = $_POST['photoid'];
if($project->updateProject($_DB, $projectid)) {
$feedback = "OK";
} else {
$feedback = "NOT OK";
}
}
Results in this:
ID || photo || sequence
1 || || 4
2 || || 2
So, what do I have to do to just update the sequence-value in the database without touching the rest of the data in the database...
FUNCTION:
public function updateProject($db, $id) {
$sql = "UPDATE tblProject SET
sequence = '".$db->escape($this->sequence)."'
WHERE id = '".$id."'";
return $db->insert($sql);
}
INSERT FUNCTION:
public function insert($sql) {
mysql_query($sql, $this->_connection);
return mysql_affected_rows($this->_connection);
}
There must be a problem with your $project->updateProject() function.
Try with simple query:
$qry = "UPDATE tblProject SET sequence = '".$project->sequence."'
WHERE ID =".(int)$projectid.";
mysql_query($qry);
Basically, whenever you get this problem, you are updating your table without any WHERE clause. Like the code below:
UPDATE myTable SET myField = 'newValue';
In this case, all of your stored records will update with the new value.
Use a WHERE clause in your query to update just one or some specified records.
UPDATE myTable SET myField = 'newValue' WHERE tableId = 'yourId';
I am trying to submit data to a database. I have an update form that has several fields on it that pulls data from the database into the fields. Submitting it updates the data in the database. The two fields i am concerned with our two image uploaders that i have in the form. I have been doing this successfully when i have only one image uploader on the page, but can't wrap my head around the conditional syntax when i add the second one. Below is the code that i am using for the forms that have only one image uploader. It looks to see if that submitted element is empty. If so, it runs an update statement and leaves out the image variable. If the image variable is not empty it runs an update statement with that field added to the statement.
if($imgProfileFull == ""){
$query = "update students set `nameFirst` = '$nameFirst', `nameLast` = '$nameLast', `profile` = '$profile', `priority` = '$priority', `active` = '$active', `_modifiedDate` = '$_modifiedDate' where `id` = '$id'";
}else{
if((($_FILES["image"]["type"] == "image/jpeg")
|| ($_FILES["image"]["type"] == "image/pjpeg"))
&& ($_FILES["image"]["size"] < 500000))
{
if($_FILES["image"]["error"] > 0){
header("location:students.php?file=error");
}else{
move_uploaded_file($_FILES["image"]["tmp_name"],
"../images/students/full/" . $imgProfileFull);
}
}else{
header("location:students.php?file=error");
}
$query = "update students set `imgProfileFull` = '$imgProfileFull', `nameFirst` = '$nameFirst', `nameLast` = '$nameLast', `profile` = '$profile', `priority` = '$priority', `active` = '$active', `_modifiedDate` = '$_modifiedDate' where `id` = '$id'";
}
How would i write my update statement to include another image field. The variable would be $imgProfileThumb. Basically i want to update the two image columns in the database if, and only if, they are NOT empty. This is because the way the form is built, the image field is technically always empty unless an image actually gets uploaded. Any thoughts? Thanks!!
You can use an if statement to create your query dynamically.
$query = "UPDATE students SET ";
if ($imgProfileFull !== ""){
$query .= "`imgProfileFull` = '$imgProfileFull', ";
}
if ($imgProfileThumb !== ""){
$query .= "`imgProfileThumb` = '$imgProfileThumb', ";
}
$query .= "`nameFirst` = '$nameFirst',
`nameLast` = '$nameLast',
`profile` = '$profile',
`priority` = '$priority',
`active` = '$active',
`_modifiedDate` = '$_modifiedDate'
WHERE `id` = '$id'";
You may also wish to use mysql_real_escape_string for your string data if you are not already doing so.