Question

Im trying to rename an image to the product id using php.

This code currently does save the image but it does not rename the file to id.jpg. 1.jpg 2.jpg 3.jpg etcetc instead it is just .jpg

How do i get it in accordance to the ID.

<?php 
// Parse the form data and add inventory item to the system
if (isset($_POST['product_name'])) {

    $product_name = mysql_real_escape_string($_POST['product_name']);
    $price = mysql_real_escape_string($_POST['price']);
    $category = mysql_real_escape_string($_POST['category']);

    $details = mysql_real_escape_string($_POST['details']);
    $stock = mysql_real_escape_string($_POST['stock']);
    // See if that product name is an identical match to another product in the system
    $sql = mysql_query("SELECT id FROM products WHERE product_name='$product_name' LIMIT 1");
    $productMatch = mysql_num_rows($sql); // count the output amount
    if ($productMatch > 0) {
        echo 'Sorry you tried to place a duplicate "Product Name" into the system, <a href="inventory_list.php">click here</a>';
        exit();
    }
    // Add this product into the database now
    $sql = mysqli_query($link,"INSERT INTO products (product_name, price, details, category, stock, date_added) 
        VALUES('$product_name','$price','$details','$category', $stock, now())") or die (mysql_error());
     $pid = mysqli_insert_id($pid);
    // Place image in the folder 
    $newname = "$pid.jpg";
    move_uploaded_file( $_FILES['fileField']['tmp_name'], "inventory_images/$newname");
    header("location: list.php"); 
    exit();
}
?>
Was it helpful?

Solution

You forgot to give the $link from your mysqli_query to the mysqli_insert_id. So the following line:

$pid = mysqli_insert_id($pid);

must be:

$pid = mysqli_insert_id($link);

Check your PHP Error Settings. You should have seen an appropriate Error since you've given an undefined variable to a method expecting an mysqli link.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top