PHP + MySql: a particular DELETE function - php

I have a table with all the product's info.
PRODUCT TABLE
produc_id
product_name
img1
img2
img3
I created a page to update the product's info. My problem is how to manage the images. In the variables img1, img2 and img3 I saved the path of the images. Now i would like to delete that record with a link in the update.php page.
I tried something like this:
<a href="delete_img.php?id=<?php echo $img1; ?>&product_id=<?php echo $product_id; ?>">
the delete_img.php page is:
<?php
include '../asset/inc/auth.inc.php';
include '../asset/inc/db.inc.php';
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
$img1 = (isset($_GET['img1'])) ? $_GET['img1'] : 0;
$product_id = (isset($_GET['product_id'])) ? $_GET['product_id'] : 0;
$query = 'UPDATE product SET img1=NULL WHERE product_id = ' . $product_id;
// invio la query
$result = mysql_query($query);
if (!$result) {
die("Errore nella query $query: " . mysql_error());
}
// close
mysql_close();
header('Refresh: 0; URL=update_immobile.php?id=' . $immobile_id . '');
?>
It works fine, but just for the single variable img1. For the second image, if I want to delete it i need another delete_img.php script (delete_img2.php) and so on.
Question: how can I optimize this 'function'?

You can optimize this function in a lot of different ways. In the $imgid could be the ID of the image stored (1, 2 or 3), therefore the HTML code would look as followed:
<a href="delete_img.php?id=<?=$imgid?>&product_id=<?php echo $product_id; ?>">
With this information submitted you can easily alter your MySQL query in the PHP code.
switch($_GET["id"]) {
case 1:
case 2:
case 3:
$field = "img" . $_GET["id"] ;
break ;
default:
$field = "" ;
}
if($table!="") {
$query = "UPDATE product SET $field=NULL WHERE product_id = $product_id";
$result = mysql_query($query);
}
More suitable would be, if you would create two more tables:
a table which stores the image + path
an intermediary table which links the image to a product
This way a product can store more than only three images and multiple products can have the same image. Also every image gets a unique ID to delete it (which would make your problem easier to solve).

This should work with as many image columns you have (not tested, but you get the idea):
<?php
include '../asset/inc/auth.inc.php';
include '../asset/inc/db.inc.php';
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD) or
die ('Unable to connect. Check your connection parameters.');
mysql_select_db(MYSQL_DB, $db) or die(mysql_error($db));
$img = (isset($_GET['img1']) && in_array(key($_GET['img1'], array('img1', 'img2', 'img3')))) ? key($_GET['img1']) : 0;
$product_id = (isset($_GET['product_id'])) ? (int)$_GET['product_id'] : 0;
if ($img !== 0) {
$query = 'UPDATE product SET ' . $img . '=NULL WHERE product_id = ' . $product_id;
// invio la query
$result = mysql_query($query);
}
if (!$result) {
die("Errore nella query $query: " . mysql_error());
}
// close
mysql_close();
header('Refresh: 0; URL=update_immobile.php?id=' . $immobile_id . '');
?>
Some notes:
* don't forget to validate user input (I made some small tweaks to the code)
* always use exit or die after sending a redirect header, otherwise anyone could access your admin area with no username/password required

$img1 = (isset($_GET['img1'])) ? $_GET['img1'] : 0;
$img2 = (isset($_GET['img2'])) ? $_GET['img2'] : 0;
$img3 = (isset($_GET['img3'])) ? $_GET['img3'] : 0;
$query = 'UPDATE product SET if($img1==0) img1=NULL' ;
$query .= 'if($img2==0) ,img2=NULL' ;
$query .= 'if($img3==0) ,img3=NULL' ;
$query .= 'WHERE product_id = ' . $product_id'
$result = mysql_query($query);
It is simply concatenation of query with if condition.

Related

Switched computers and get two new mysqli_fetch_row errors.

after I managed to connect my website form to my database, I decided to try to transfer over my files to my work computer.
Initially I only had one error: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in...
However now I get an extra mysqli_fetch_row() error the same as above but the error is on a different line.
Additionally I also get the error: Undefined index: fill which I never got before. Are there any mistakes in my code? The form still works and can connect to my database.
<center><form action="fill.php" method="post">
Fill
<input type="text" id="fill"" name="fill">
<input type="submit" id ="submit" name="submit" value="Submit here!">
</form></center>
</div>
<?php
$val1 = $_POST['fill'];
$conn = mysqli_connect('localhost', 'root', '')or
die("Could not connect");
mysqli_select_db($conn, 'rfid');
$val2 = "SELECT * FROM card_refill WHERE refill = $val1";
$result1= $conn->query($val2);
$row = mysqli_fetch_row($result1);
$refill1 = $row[2];
$value = "SELECT *FROM card_credit ORDER BY id DESC LIMIT 1:";
$result = $conn->query($value);
$row = mysqli_fetch_row($result);
$refill = $row[2];
$money= $refill+$refill1;
echo $money;
$sql = "UPDATE card_credit SET value = '$money'";
if ($conn->query($sql) === TRUE) {
echo "Success";
}
else {
echo "Warning: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
</body>
</html>
You're getting that error because you use $_POST['fill'] without checking whether it's set first. It will only be set when the form is submitted, not when the form is first displayed. You need to put all the code that processes the form input into:
if (isset($_POST['submit'])) {
...
}
BTW, you can do that entire update in a single query.
UPDATE card_credit AS cc
CROSS JOIN card_refill AS cr
CROSS JOIN (SELECT * FROM card_credit ORDER BY id DESC LIMIT 1) AS cc1
SET cc.value = cr.col2 + cc1.col2
WHERE cr.refill = '$val1'
Like GolezTrol said from his comment. You're mixing object and functional notation.
Although this might not work exactly how you need it to because I don't have all the information. I have written you something I think is close to what you're looking for.
<?php
// Define the below connections via $username = ""; EXTRA....
// This is best done in a separate file.
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$val1 = $_POST['fill'];
$result1 = $conn->query("SELECT * FROM card_refill WHERE refill = '$val1' ");
$result2 = $conn->query("SELECT * FROM card_credit ORDER BY id DESC LIMIT 1:");
$refill1 = array(); // Pass Results1 Into Array
while($row = $result1->fetch_assoc()) {
$refill1[] = $row[2];
}
$refill = array(); // Pass Results2 Into Array
while($row = $result2->fetch_assoc()) {
$refill[] = $row[2];
}
/* Without an example of what data you are getting from your tables you will have to figure out what data you want from the arrays.
$money= $refill+$refill1;
echo "DEBUG: $money";
*/
// This code will not be functional until your populate the $money value.
$sql = "UPDATE card_credit SET value = '$money' ";
if ($conn->query($sql) === TRUE) {
echo nl2br("Record updated successfully"); // DEBUG
print_r(array_values($refill1)); // DEBUG
print_r(array_values($refill)); // DEBUG
echo nl2br("\n"); // DEBUG
} else { // DEBUG
echo "Error updating record: " . $conn->error; // DEBUG
echo nl2br("\n"); // DEBUG
}
$conn->close();
?>

Database not updating when using PHP var's

I am doing some simple PHP and SQL for the first time in quite a while, but for some reason am not getting it to work. When I provide fixed values it all works fine, but as soon as I replace them with variables my code fails. I have checked and it seems that the variables have proper values in them:
This works:
<?php
$con=mysqli_connect("localhost","xxx","xxx","xxx");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_GET['id'])){
$ID = $_GET['id'];
$newStock = $_GET['stockcount'] - 1;
mysqli_query($con,'UPDATE products SET stockcount = "3" WHERE id = "1"');
}
else
echo "Invalid item";
mysqli_close($con);
header('Location: browse.php');
?>
But not this:
<?php
$con=mysqli_connect("localhost","xxx","xxx","xxx");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_GET['id'])){
$ID = $_GET['id'];
$newStock = $_GET['stockcount'] - 1;
mysqli_query($con,'UPDATE products SET stockcount = "'+$newStock+'" WHERE id = "'+$ID+'"');
}
else
echo "Invalid item";
mysqli_close($con);
header('Location: browse.php');
?>
Do I need to do something with the variables, or am I doing something else wrong? As always, any advice would be greatly appreciated :)
" + " is not used for concatenate string in PHP as you did
mysqli_query($con,'UPDATE products SET stockcount = "'+$newStock+'" WHERE id = "'+$ID+'"');
it should be as
mysqli_query($con,'UPDATE products SET stockcount = "'.$newStock.'" WHERE id = "'.$ID.'"');
mysqli_query($con,'UPDATE products SET stockcount = "'.$newStock.'" WHERE id = "'.$ID.'"');
This isn't javascript. Connotate with . not +. Better yet, just pass it in string by using double-quotes!
mysqli_query($con,"UPDATE products SET stockcount = '$newStock' WHERE id = '$ID'");

updating a flag in mysql via radiobutton onclick handler in php

I want to update a column in a table in mysql. Basically the column is the flag for the entries of that db table.
The modification of the column is resetting all values to 0 and setting the desired row to 1, for this reason I have post.php file which looks like
<?php
require_once('class.uuid.php');
$connection = mysql_connect("---logindetailshere---");
$db = mysql_select_db("---dbnamehere---",$connection);
switch($_REQUEST['action']){
case ...
break;
case ...
break;
case 'changeDisp':
changeDisp($_REQUEST['uid']);
break;
}
mysql_close($connection);
...
function changeDisp($uid){
global $connection, $db;
$q_string = "UPDATE Questions SET Displayed = 0";
$query = mysql_query($q_string,$connection) or die( sendError(mysql_error() . '<br/><br/>' . $q_string) );
$q_string = "UPDATE Questions SET Displayed = 1 WHERE Uid='${uid}'";
$query = mysql_query($q_string,$connection) or die( sendError(mysql_error() . '<br/><br/>' . $q_string) );
}
?>
on the webpage I display the items and radiobuttons next to the items, the purpose is to select the radiobuttons and post to set the flag 1 for the selected item, for this reason I have a item.php file
<?php
$i = 1;
foreach ($qitem as &$q) {
$options = explode(";", $q["Options"]);
$displayed = '';
if ($q["Displayed"] == 1) { $displayed='checked="yes"'; }
echo("<div class='item' name='".$q["iUid"]."'>");
echo("<div class='count'>".$i.".</div>");
echo ("<div class='radio'><input type='radio' onclick='changeDisp("".$q["Uid"]."")' name='disp' ".$displayed."></div>");
echo("<div class='left'>");
echo("<h4>".$q["Value"]."</h4>");
echo("<div class='details'>Typ: ".$q["Type"]."</div>");
echo("<div class='details'>Skala: ".$options[0]." / ".$options[1]."</div>");
echo("</div>");
echo("</div>");
$i++;
}
?>
here I am using radiobuttons to select the related item, I checked the unique id values using firebug the values are fine, I just want to click on any radiobutton and want to trigger the onclick=changeDisp() function.
I have no idea why the page doesn't reload itself and change the selected flag to 1. Could you please help me to solve this problem?
Thanks in advance.
You cannot use an onclick function to call php function without going there with a javascript, jQuery or ajax call. You could create an ajax script to call the post.php From the item.php page and return the results to you.
Here is an example of creating the function you want. This assumes that $uid is coming from a radio button and not an actual user input. If the user can directly input something you need to use a prepared statment
function changeDisp($uid)
{
$Mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if ($Mysqli->connect_errno)
{
echo "Failed to connect to MySQL: (" . $Mysqli->connect_errno . ") " . $Mysqli->connect_error;
$Mysqli->close();
}
$query = "UPDATE Questions SET Displayed = 1 WHERE Uid='".$uid."'";
$update = $Mysqli->query($query);
if($update)
{
return true;
}
return false;
}

PHP database connection failed

I have a php file that includes two functions, one to connect to the database and one to set cookied for the cart. Here is that file:
<?php
$dbServer="localhost";
$dbName="test";
function ConnectToDb($server, $database){
$s=#mysql_connect($server);
$d=#mysql_select_db($database, $s);
if(!$s || !$d)
return false;
else
return true;
}
function GetCartId(){
if(isset($_COOKIE["cartId"])){
return $_COOKIE["cartId"];
}
else {
session_start();
setcookie("cartId", session_id(), time()+((3600*24)*30));
return session_id();
}
}
?>
The function for connecting to the database works well in another php file for this particular program. I am having a problem with it in this file:
<?php
include("db.php");
switch($_GET["action"]) {
case "add_item":
{
AddItem($_GET["id"], $_GET["qty"]);
ShowCart();
break;
}
case "update_item": {
UpdateItem($_GET["id"], $_GET["qty"]);
ShowCart();
break;
}
case "remove_item": {
RemoveItem($_GET["id"]);
ShowCart();
break;
}
default: {
ShowCart();
}
}
function AddItem($itemId, $qty) {
// Will check whether or not this item
// already exists in the cart table.
// If it does, the UpdateItem function
// will be called instead
$cxn = #ConnectToDb($dbServer, $dbName);
// Check if this item already exists in the users cart table
$result = mysql_query("select count(*) from cs368_cart where cookieID = '" . GetCartID() . "' and itemId = $itemId");
$row = mysql_fetch_row($result);
$numRows = $row[0];
if($numRows == 0) {
// This item doesn't exist in the users cart,
// we will add it with an insert query
#mysql_query("insert into cs368_cart(cookieID, itemId, qty) values('" . GetCartID() . "', $itemId, $qty)");
}
else {
// This item already exists in the users cart,
// we will update it instead
UpdateItem($itemId, $qty);
}
}
function UpdateItem($itemId, $qty) {
// Updates the quantity of an item in the users cart.
// If the qutnaity is zero, then RemoveItem will be
// called instead
$cxn = #ConnectToDb($dbServer, $dbName);
if($qty == 0) {
// Remove the item from the users cart
RemoveItem($itemId);
}
else {
mysql_query("update cs368_cart set qty = $qty where cookieID = '" . GetCartID() . "' and itemId = $itemId");
}
}
function RemoveItem($itemId) {
// Uses an SQL delete statement to remove an item from
// the users cart
$cxn = #ConnectToDb($dbServer, $dbName);
mysql_query("delete from cs368_cart where cookieID = '" . GetCartID() . "' and itemId = $itemId");
}
function ShowCart() {
// Gets each item from the cart table and display them in
// a tabulated format, as well as a final total for the cart
$cxn = #ConnectToDb($dbServer, $dbName);
$result = mysql_query("select * from cs368_cart inner join cs368_products on cart.itemId =
items.itemId where cart.cookieID = '" . GetCartID() . "' order by items.itemName asc")
or die("Query to get test in function ShowCart failed with error: ".mysql_error());
?>
What can I do the remedy this problem? Thanks!
First: lose the #, and put some proper error handling in there (those functions return false when something goes wrong, and you can use mysql_error and mysql_errno to log it).
Second: mysql_real_escape_string and intval on those $_GET parameters before someone sneaks in some extra code through the URL.
Third: you're accessing $dbServer and $dbName as variables local to the function UpdateItem, rather than global to the script. You should only connect to the database once (in the original db.php file), and let the query functions take care of the rest (since there's only one connection, they all default to that one anyway).

How to delete an image using PHP & MySQL?

I was wondering if some one can give me an example on how to delete an image using PHP & MySQL?
The image is stored in a folder name thumbs and another named images and the image name is stored in a mysql database.
Delete the file:
unlink("thumbs/imagename");
unlink("images/imagename");
Remove from database
$sql="DELETE FROM tablename WHERE name='imagename'"
$result=mysql_query($sql);
Assuming name is the the name of the field in the database holding the image name, and imagename is the image's name.
All together in code:
$imgName='sample.jpg';
$dbFieldName='name';
$dbTableName='imageTable';
unlink("thumbs/$imgName");
unlink("images/$imgName");
$sql="DELETE FROM $dbTableName WHERE $dbFieldName='$imgName'";
mysql_query($sql);
try this code :
$img_dir = 'image_directory_name/';
$img_thmb = 'thumbnail_directory_name/';// if you had thumbnails
$image_name = $row['image_name'];//assume that this is the image_name field from your database
//unlink function return bool so you can use it as conditon
if(unlink($img_dir.$image_name) && unlink($img_thmb.$image_name)){
//assume that variable $image_id is queried from the database where your image record your about to delete is...
$sql = "DELETE FROM table WHERE image_id = '".$image_id."'";
$qry = mysql_query($sql);
}else{
echo 'ERROR: unable to delete image file!';
}
Are you looking for actual code or just the idea behind it?
You'll need to query the db to find out the name of the file being deleted and then simply use unlink to delete the file in question.
so here's some quick code to get you started
<?php
$thumb_dir = "path/to/thumbs/";
$img_dir = "path/to/images/";
/* query your db to get the desired image
I'm guessing you're using a form to delete the image?
if so use something like $image = $_POST['your_variable'] to get the image
and query your db */
// once you confirm that the file exists in the db check to see if the image
// is actually on the server
if(file_exists($thumb_dir . $image . '.jpg')){
if (unlink($thumb_dir . $image . '.jpg') && unlink($img_dir . $image . '.jpg'))
//it's better to use the ID rather than the name of the file to delete it from db
mysql_query("DELETE FROM table WHERE name='".$image."'") or die(mysql_error());
}
?>
if(!empty($_GET['pid']) && $_GET['act']=="del")
{
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".$_DIR['site']['adminurl']."mservices".$atend."suc".$_DELIM."3".$baratend);
exit();
}
}
$_sql = "SELECT * FROM mservices WHERE pro_id=".$_GET['pid'];
$rs = $_CONN->Execute($_sql);
if ($rs->EOF) {
$_MSG[] = "";
$error = 1;
}
if ($rs)
$rs->close();
if (!$error) {
$_Image_to_delete = "select pro_img from mservices where pro_id=".$_GET['pid'];
$trial=$_CONN->Execute($_Image_to_delete);
$img = trim(substr($trial,7));
unlink($_DIR['inc']['product_image'].$img);
$_sql = "delete from mservices where pro_id=".$_GET['pid'];
$_CONN->Execute($_sql);
header("Location: ".

Categories