2

I have been going mad trying to work out why insert_id is returning 0 within my database. I upload an image, then upload the which category it is under and a brief description with the image_id (Which should be taken from the insert_id) I cannot figure out why it is not working.

The upload image function is :

function postImageShare($image_name)
{
    global $BEAR;

    if ($stmt = $BEAR->Database->prepare("INSERT INTO images SET account_name = '".$_SESSION['account_name']."', image_name = ?"))
    {
        $stmt->bind_param('s', $image_name);
        $stmt->execute();
        //$stmt->close();   
    }       

    $lastItemID  = $BEAR->Database->insert_id;
    return $lastItemID; 
}

Then the function which Inserts the description/image_id and category (called hoard) is the following:

function postImageShareInformation($description, $hoard_id)
{
    global $BEAR;

    if ($stmt = $BEAR->Database->prepare("INSERT INTO imagesInformation SET account_name = '".$_SESSION['account_name']."', image_id = '$lastItemID', description = ?, hoard_id = ? "))
    {
        $stmt->bind_param('si', $description, $hoard_id);
        $stmt->execute();
        $stmt->close(); 
    }   

}

When I run the above the database is populated effectively except for the image_id is 0 everytime. When I have run the above i also get a notice in regards to $lastIteID. I tried placing the

        $lastItemID  = $BEAR->Database->insert_id;

in the second 'postImageShareInformation' function and the inserted result is still 0. Both tables hi id fields that are auto-incremementing, and $BEAR is my connection to the database. Any help would be appreciated as this issue is driving me mad.

UPDATED :

The Html :

<form action=" " id="share_form" method="post" enctype="multipart/form-data">
       <input type="file" id="share_image" name="share_image" style="display:none"/>
       <div id="upload-image-button" class="uibutton-upload">Choose Image</div>        
</form>

The above is the form to upload the image, which is done via j'query and PHP below:

 $(document).ready(function() { 
        $('#share_image').live('change', function(){ 
            $("#preview_share").html('');
            $("#preview_share").html('<div class="loading_bar"><div id="image_bar" class="bar"><span></span></div></div>');

            $("#share_form").ajaxForm({
                target: '#preview_share'
            }).submit();
    });
}); 

Then to upload the image description and hoard is via this form:

<form autocomplete="off" enctype="multipart/form-data" method="post" name="form">
    <input type="text" name="description"/><br/>
    <input type="text" name="hoard_id"/><br/>
    <input type="submit" value="submit"> 
 </form>

And this is the php which uses the functions:

 if(isset($_POST['description']))
{   // Set and Clean Variables
    $BEAR->Template->setData('description', $_POST['description'], TRUE);
    $BEAR->Template->setData('hoard_id', $_POST['hoard_id'], TRUE);
    $BEAR->Webprofile->postImageShareInformation($BEAR->Template->getData('description'), $BEAR->Template->getData('hoard_id'));
}

else if(isset($_FILES['share_image']) )
{
    $valid_formats = array("jpg", "jpeg", "png");

    $name = $_FILES['share_image']['name'];
    $size = $_FILES['share_image']['size'];

    if ($size > 2097152)
    {
        echo '<div class="image_error">Photo Too Large</div>';
    }
    else if(strlen($name))
    {

        list($txt, $ext) = explode(".", $name);

        if(in_array($ext,$valid_formats))
        {

            // Set Image Upload Data
            $BEAR->Template->setData('actual_image_name', $_SESSION['account_name']."-".rand().time().substr(str_replace(" ", "_", $txt), 5).".".$ext);
            $tmp = $_FILES['share_image']['tmp_name'];

            // Move Location
            $location_original = "uploads/test/".$_SESSION['account_name']."/";
            $location_large = "uploads/test/".$_SESSION['account_name']."/large/";
            $location_small = "uploads/test/".$_SESSION['account_name']."/small/";

            if (!file_exists("uploads/test/" . $_SESSION['account_name']))
            {

                mkdir($location_original, 0744);
                mkdir($location_small, 0744);
                mkdir($location_large, 0744);

                move_uploaded_file($tmp, $location_original.$BEAR->Template->getData('actual_image_name'));
                $BEAR->Assets->create_thumb(125, 125, $location_original, $BEAR->Template->getData('actual_image_name'), $location_small);
                $BEAR->Assets->create_thumb(500, 500, $location_original, $BEAR->Template->getData('actual_image_name'), $location_large);

                echo "<img src='uploads/test/".$_SESSION['account_name']."/large/".$BEAR->Template->getData('actual_image_name')."'class='preview'>".$BEAR->Template->getData('actual_image_name');
            }
            else
            {
                // Move Image
                move_uploaded_file($tmp, $location_original.$BEAR->Template->getData('actual_image_name'));
                $BEAR->Assets->create_thumb(125, 125, $location_original, $BEAR->Template->getData('actual_image_name'), $location_small);
                $BEAR->Assets->create_thumb(500, 500, $location_original, $BEAR->Template->getData('actual_image_name'), $location_large);  

                $BEAR->Webprofile->postImageShare($BEAR->Template->getData('actual_image_name'));
                echo "<img src='uploads/test/".$_SESSION['account_name']."/small/".$BEAR->Template->getData('actual_image_name')."' class='preview'>";
            } 
        }
        else 
        {
            echo '<div class="image_error">Invalid File Type</div>';
        }                       
    }                        
    else
    {
        echo '<div class="image_error">Failed</div>';
    }
}

All the above allows the user to preview the uploaded image before submitting the description and Hoard ID.Hope this helps.

HireLee
  • 561
  • 1
  • 9
  • 25
  • is function `postImageShare($image_name)` returning correct `$lastItemID`? – LoneWOLFs Jan 11 '13 at 22:57
  • Hi @LoneWOLFs I tested the code and it does return the latest ID, so that is working, its just getting it to work for my next function. – HireLee Jan 12 '13 at 08:55

5 Answers5

1

Seems to me that your function postImageShareInformation($description, $hoard_id) is not getting the $lastItemID variable. So try passing the value of $lastItemID in the function itself like below.

function postImageShareInformation($description, $hoard_id, $lastItemID)
{
    global $BEAR;

    if ($stmt = $BEAR->Database->prepare("INSERT INTO imagesInformation SET account_name = '".$_SESSION['account_name']."', image_id = '".$lastItemID."', description = ?, hoard_id = ? "))
    {
        $stmt->bind_param('si', $description, $hoard_id);
        $stmt->execute();
        $stmt->close(); 
    }   

}

To the updated question

You were calling postImageShareInformation() function before calling postImageShare() function. Thus it would never get the $lastItemID. I've modified your code assuming you use my new modified functions. But this should still give you an idea.

if(isset($_FILES['share_image']) )
{
    $valid_formats = array("jpg", "jpeg", "png");

    $name = $_FILES['share_image']['name'];
    $size = $_FILES['share_image']['size'];

    if ($size > 2097152)
    {
        echo '<div class="image_error">Photo Too Large</div>';
    }
    else if(strlen($name))
    {

        list($txt, $ext) = explode(".", $name);

        if(in_array($ext,$valid_formats))
        {

            // Set Image Upload Data
            $BEAR->Template->setData('actual_image_name', $_SESSION['account_name']."-".rand().time().substr(str_replace(" ", "_", $txt), 5).".".$ext);
            $tmp = $_FILES['share_image']['tmp_name'];

            // Move Location
            $location_original = "uploads/test/".$_SESSION['account_name']."/";
            $location_large = "uploads/test/".$_SESSION['account_name']."/large/";
            $location_small = "uploads/test/".$_SESSION['account_name']."/small/";

            if (!file_exists("uploads/test/" . $_SESSION['account_name']))
            {

                mkdir($location_original, 0744);
                mkdir($location_small, 0744);
                mkdir($location_large, 0744);

                move_uploaded_file($tmp, $location_original.$BEAR->Template->getData('actual_image_name'));
                $BEAR->Assets->create_thumb(125, 125, $location_original, $BEAR->Template->getData('actual_image_name'), $location_small);
                $BEAR->Assets->create_thumb(500, 500, $location_original, $BEAR->Template->getData('actual_image_name'), $location_large);

                echo "<img src='uploads/test/".$_SESSION['account_name']."/large/".$BEAR->Template->getData('actual_image_name')."'class='preview'>".$BEAR->Template->getData('actual_image_name');
            }
            else
            {
                // Move Image
                move_uploaded_file($tmp, $location_original.$BEAR->Template->getData('actual_image_name'));
                $BEAR->Assets->create_thumb(125, 125, $location_original, $BEAR->Template->getData('actual_image_name'), $location_small);
                $BEAR->Assets->create_thumb(500, 500, $location_original, $BEAR->Template->getData('actual_image_name'), $location_large);  

                // This will return $lastItemID which we will pass now to postImageShareInformation() function in the block below.
                $lastItemID = $BEAR->Webprofile->postImageShare($BEAR->Template->getData('actual_image_name'));

                if(isset($_POST['description']))
                {   // Set and Clean Variables
                    $BEAR->Template->setData('description', $_POST['description'], TRUE);
                    $BEAR->Template->setData('hoard_id', $_POST['hoard_id'], TRUE);
                    //You were calling this function before ...
                    $BEAR->Webprofile->postImageShareInformation($BEAR->Template->getData('description'), $BEAR->Template->getData('hoard_id'),$lastItemID);
                }
                echo "<img src='uploads/test/".$_SESSION['account_name']."/small/".$BEAR->Template->getData('actual_image_name')."' class='preview'>";
            } 
        }
        else 
        {
            echo '<div class="image_error">Invalid File Type</div>';
        }                       
    }                        
    else
    {
        echo '<div class="image_error">Failed</div>';
    }
}

This should work...

Hope it helps.

LoneWOLFs
  • 2,306
  • 3
  • 20
  • 38
  • Thanks for the reply @LoneWolfs When trying to above code, the following Warning occurs - 'Missing argument 3 for postImageShareInformation()' and the same Notice: undefined varibale:lastItemID. It seems that the postImageShareInformation cannot get the $lastItemId variable... any thoughts? Thanks for your reply. – HireLee Jan 12 '13 at 09:43
  • @LeeMarshall Yes check the function i modified it and i am now passing a third variable as the `$lastItemID` so you should call your function with 3 parameters the last being `$lastItemID`. So your fn will look like this when its called `postImageShareInformation('I am image description', 1, 100)` where 100 is the data returned by `postImageShare($image_name)` function for example. – LoneWOLFs Jan 12 '13 at 09:54
  • This is exactly what I did got the error, it seems like the second function cannot get the $lastItemID. The first function is activated by j'query with the following code in the page header $(document).ready(function() { $('#share_image').live('change', function(){ $("#preview_share").html(''); $("#preview_share").html('
    '); $("#share_form").ajaxForm({ target: '#preview_share' }).submit(); }); });
    – HireLee Jan 12 '13 at 10:34
  • But that shouldn't have any effect as the function is still submitting the image effectively into the database. – HireLee Jan 12 '13 at 10:35
  • @LeeMarshall show me the html and how these functions are called. Error is in the way you call them. As it there's nothing wrong with the functions. – LoneWOLFs Jan 12 '13 at 11:53
  • I updated the question with Html and Jquery... Hope that helps, and thanks for your time. – HireLee Jan 12 '13 at 15:53
  • @LeeMarshall Check my updated answer if it helps you resolve your query – LoneWOLFs Jan 14 '13 at 06:31
  • I will be checking this tonight, and will let you know... If it works I will make it answered. Thanks buddy. – HireLee Jan 15 '13 at 16:04
0

I would say this is because your tables' id column doesn't have an AUTO_INCREMENT property

Dracony
  • 842
  • 6
  • 15
0

Now I understood what's happening here. So we have those 2 functions:

function postImageShare($image_name)
{
    global $BEAR;

    if ($stmt = $BEAR->Database->prepare("INSERT INTO images SET account_name = '".$_SESSION['account_name']."', image_name = ?"))
    {
        $stmt->bind_param('s', $image_name);
        $stmt->execute();
        //$stmt->close();   
    }       

    $lastItemID  = $BEAR->Database->insert_id;
    return $lastItemID; 
}

and

// Note that I've added a new parameter to this function and also
// I've modified your prepare statement
function postImageShareInformation($description, $hoard_id, $lastItemID)
{
    global $BEAR;

    if ($stmt = $BEAR->Database->prepare("INSERT INTO imagesInformation SET account_name = '".$_SESSION['account_name']."', image_id = ?, description = ?, hoard_id = ? "))
    {
        $stmt->bind_param('si', $lastItemID, $description, $hoard_id);
        $stmt->execute();
        $stmt->close(); 
    }   

}

Now, when we call the first one we have to assign the returned id to a variable:

$lastItemID = postImageShare("myImageName");

When we call the second function we can assign this variable to the last parameter:

postImageShareInformation("My description", 13, $lastItemID);

Now should be just fine!

Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
-1

I assume that $Bear object is not a direct mysqli connection.. It is a class created by you?

If you have

$mysqli = new MySQLi($host, $user, $password, $db_name);

then after you run the query

$mysqli->query("INSERT INTO test VALUES ('test')");

you can get the last inserted id by

$mysqli->insert_id
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
  • Hi Matei, the $BEAR is in my function __construct. Which is basically $this->Database = new mysqli($server, $user, $pass, $db) ... So surely me using $BEAR->Database->insert_id this should return the last id? or am i missing something? – HireLee Jan 12 '13 at 08:47
-1

MySQL provides this functionality in the last_insert_id() function.

hd1
  • 33,938
  • 5
  • 80
  • 91