views:

108

answers:

4

Hi

I'm trying to make a website in which a user inputs details on one screen, and they are posted onto the following script. This script is meant to store these details in a database along with a unique integer ID (which it does), and then generate two links containing the unique ID of the record just created. Since the database creates the ID rather than the page before, I've tried to query the database for the most recent record (i.e. the one with the highest unique ID value) and use that number in the link, however with the current script the ID doesn't seem to show up in the page. Is it a variable type thing? Is there a simpler way to get the ID of the page just created? Here's the code:

$css = $_POST['css'];
$shopName = strip_tags($_POST['title']);
$email = $_POST['email'];

$con = mysql_connect("***","***","***");
if (!$con)
{
    die('Could not connect to database: '. mysql_error());
}

mysql_select_db("***", $con);

$sql = "INSERT INTO wps_Shops (shopName, shopEmail, shopStyle)
 VALUES ('$shopName', '$email', '$css')";

$quer = mysql_query($sql);

$result = mysql_query("SELECT *
     FROM wps_Shops
     ORDER BY shopId DESC
     LIMIT 1");

$lastShop = mysql_fetch_array($result);

$id = strval($lastShop['id']);

echo ("Id: ".$id);

if ($quer)
{
    echo("<h1>Shop created</h1>");
    echo("<p><a href=\"shop.php?id=$id\">Go to shop</a></p>");
    echo("<p><a href=\"addproducts.php?id=$id\">Add products</a></p>");
}

mysql_close($con);
+2  A: 

You need mysql_insert_id.

Milen A. Radev
+1  A: 

Is it called 'id' or 'shopId' ? But you should use: http://php.net/mysql_insert_id

Erik
+2  A: 

Right after you do the mysql_query() for the insert, you can use mysql_insert_id() to get the ID of the inserted row.

mysql_query("INSERT INTO........");
$id=mysql_insert_id();


Click Upvote
+1  A: 

Alternatively, you can make the following MySQL query:

$query = "SELECT * FROM wps_Shops WHERE id=LAST_INSERT_ID()";
$result = mysql_query($query);

Though I'm confused as to why you used ORDER BY shopId but in a later line call:

$id = strval($lastShop['id']);

Also, is there really any need to make that strval() call? PHP already does that type conversion for you when you call echo(). And, currently, any result data returned from either, mysql_query() or mysqli_query(), is returned in string format, regardless of that column's data type in MySQL.

Calvin