benwad
benwad

Reputation: 6604

Echoing an integer from a mySQL database

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);

Upvotes: 1

Views: 468

Answers (4)

Calvin
Calvin

Reputation: 4619

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.

Upvotes: 1

Ali
Ali

Reputation: 267317

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();

Upvotes: 2

Erik
Erik

Reputation: 4105

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

Upvotes: 1

Milen A. Radev
Milen A. Radev

Reputation: 62683

You need mysql_insert_id.

Upvotes: 2

Related Questions