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.
Related
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);
}
I have a problem when trying to update table after checking row. Not sure if the "if" statement is wrong, however I'm not quite sure, why the UPDATE sql is returning this error. I wouldn't be suprised if INSERT did that.
Here's part of code:
$sql = "SELECT user_id FROM players WHERE user_id = '$id'";
$result = $connect->query($sql);
if($result->num_rows > 0)
{
$sql = "UPDATE players SET user_id = '$Player->user_id', display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
if($connect->query($sql) === TRUE)
{
echo 'Table has been successfully updated.';
}else{
echo 'There has been a problem with updating the "players" table. <br>Error: '.$connect->error;
}
}else{
$sql = "INSERT INTO players(user_id, display_name, attackPower, defensePower) VALUES('$Player->user_id', '$Player->display_name', '$Player->attackPower', '$Player->defensePower')";
if($connect->query($sql) === TRUE)
{
echo'Table has been successfully migrated.';
}else{
echo'Table migration has failed.';
}
}
$connect->close();
INSERTing is working just fine. I would appreciate any advice. Thanks.
Your update query should look like:
$sql = "UPDATE `players` SET `display_name` = '{$Player->display_name}',
`attackPower` = '{$Player->attackPower}', `defensePower` = '{$Player->defensePower'}
WHERE `user_id` = '{$Player->user_id}'";
It cause an error because Identity columns are not updateable.
You can update every columns except them:
$sql = "UPDATE players SET display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
As #aynber and #Julqas said, problem was my sql was missing WHERE condition. Thanks for help.
I'm trying to write a query to check which column to update. The user sends an action which they performed (a like or a comment) and I'm trying to update a table. Is it possible to check inside the query which column to update? For example:
DB structure:
id imageName imageLikesCount imageCommentsCount
$actionPerformed = "like";
mysqli_query($link, "UPDATE table (if $actionPerformed=like SET imageLikesCount+1
else imageCommentsCount+1)
WHERE imageName='$image'");
I'm not sure how to phrase that, if it's possible at all. Any advice? Thanks in advance!
though meverhart913 has a way to do it, the better way to do the same thing is to instantiate your variable based on the if condition, then just plug that variable into your string. This keeps you from having to repeat your string over and over as well as allows you to easily add additional conditions.
if($actionPerformed=="like"){
$col = imageLikesCount;
else{
$col = imageCommentsCount;
}
mysqli_query($link, "Update table SET '$col' = '$col + 1' where imageName = '$image'");
if($actionPerformed=="like"){
mysqli_query($link, "Update table SET imageLikesCount = imageLikesCount + 1 where imageName = '$image'");
}
else {
mysqli_query($link, "Update table SET imageCommentsCount = imageCommentsCount + 1 where imageName = '$image'");
}
I'm not a php programmer so my syntax won't be correct, but here are two ways to do it:
if ($actionPerformed == "like")
query for updating imageLikesCount
else if ($actionPerformed == "comment")
query for updating imageCommentsCount
else
whatever
Or
if ($actionPerformed == "like")
$column = "imageLikesCount";
else ($actionPerformed == "comment")
$column = "imageCommentsCount";
$sql = "update table set $column = $column + 1";
Then execute it.
I'm trying to add a value to a row in a database table that currently has other values. I want to effect only one field in the table. here's what I'm doing:
$sql = "UPDATE users SET photo = ".$m_fname." WHERE pin = ".$_SESSION['pin'].";";
What's the correct way to do this?
Here's a little more:
$m_fname = mysql_real_escape_string($dest_filename);
$sql = "UPDATE users SET photo = ".$m_fname." WHERE pin = ".$_SESSION['pin'].";";
$res = #mysql_query($sql);
if (!$res) {
$errors[] = "Could not run query.";
break;
}
Before anyone else downvotes..
I'm aware I should be using mysqli. Sorry if I offended anyone by using an old function.
Maybe this helps, it's a different implementation and it includes a proper way of data-sanitation:
$dbSession = new PDO('mysql:host=***;dbname=***', '***', '***');
$updateQuery = $dbSession->prepare('
UPDATE
`users`
SET
`photo` = :photo
WHERE
`pin` = :pin');
$updateQuery->bindParam(':photo', $m_fname, PDO::PARAM_STR);
$updateQuery->bindParam(':pin', $_SESSION['pin'], PDO::PARAM_INT); // or 'PARAM_STR'
$updateQuery->execute();
See documentation for more functions available:
PHP Database Objects
Since you are setting the field photo to a string value, consider using single qutation
$sql = "
UPDATE `users`
SET `photo` = '" . $m_fname . "'
WHERE `pin` = " . $_SESSION['pin']; // Not clear what pin is (string or int)
What is the problem that you are facing? the code seems to be fine, provided that the PIN field is the primary unique key, and that photo is a varchar
use "'" for non number
$sql = "UPDATE users SET photo = '".$m_fname."' WHERE pin = '".$_SESSION['pin']."';";
$m_fname = mysql_real_escape_string($dest_filename);
$sql = "UPDATE users SET photo = '{$m_fname}' WHERE pin = '{$_SESSION['pin']}';";
$res = #mysql_query($sql);
if (!$res) {
$errors[] = "Could not run query.";
break;
}
How would I not include text fields of a form left blank in a MySQL update query? I understand why it's replacing filled fields with empty strings, but I'm not sure of an efficient way to fix it. Is the best option really just a lot of if statements? Is there some kind of function I could use to disallow blank fields in my html form?
Here's what I have so far:
//Check if record exists
if(mysql_num_rows(mysql_query("SELECT Item_Id FROM Item_t WHERE Item_Id = '$itemid'")) == 0){
die('The Item ID you entered was not found. Please go back and try again.');
}
//Update record
$update = "UPDATE Item_t SET Item_Name='$itemname', Item_Price='$itemprice' WHERE Item_Id='$itemid'";
mysql_query($update);
So basically, in this example, if you leave the field that sets $itemname blank and just update $itemprice, the price will be updated, but the name will be set to an empty string.
You can check if your strings are empty in the SQL:
UPDATE Item_t
SET Item_Name = IF('$itemname' = '', Item_Name, '$itemname'),
Item_Price = IF('$itemprice' = '', Item_Price, 'itemprice')
WHERE Item_Id='$itemid'
If you're building the update string in php, you might as well just build it differently if it's empty:
$update = "UPDATE Item_t SET ".($itemname ? "Item_Name='$itemname', " : "")."Item_Price='$itemprice' WHERE Item_Id='$itemid'";
try something like this.
$strSet = '';
//make sure to sanitize your inputs first, then do this....
if(Item_Name != ''){ $strSet .= 'Item_Name=\'$itemname\','};
if(Item_Price != ''){ $strSet .= 'Item_Price=\'$itemprice\','};
//removes trailing comma
$strSet = substr($strSet,0,-1);
//Update record
$update = "UPDATE Item_t SET " . $strSet . " WHERE Item_Id='$itemid'";
mysql_query($update);