I'm trying to get the row ID after the slug (ex. post 1 returns "/bligpost.php?id=1").
Instead, it returns no ID.
Where am I doing it wrong? (I have included my other attempts in comments.)
mysql_connect("$hosty","$uname","$paswd");
#mysql_select_db($dbnme) or die( "Unable to select database");
$name=$_POST['Title'];
$slug="blogpost.php?id=";
$auth=$_POST['Author'];
$date=$_POST['Date'];
$cont=$_POST['Content'];
//$query = ("INSERT INTO Blogs (Name, URL, Content, Author, Date) VALUES ('$name', '$slug', '$cont', '$auth', '$date')");
mysql_query("INSERT INTO Blogs (id, Name, URL, Content, Author, Date) VALUES (NULL, '$name', '$slug', '$cont', '$auth', '$date')");
//$pind = mysql_query("SELECT LAST_INSERT_ID()");
mysql_query("UPDATE Blogs SET URL=blogpost.php?id=`id` WHIERE id=LAST_INSERT_ID()");
//mysql_query("UPDATE Blogs SET URL=blogpost.php?id=".$pind." WHERE Content=".$cont);
mysql_close();
Try with mysql_insert_id() like
mysql_query("INSERT INTO Blogs (id, Name, URL, Content, Author, Date) VALUES (NULL, '$name', '$slug', '$cont', '$auth', '$date')");
$id = mysql_insert_id();
echo "My Last Inserted Id ".$id;
Tr this LINK And dont use mysql_* functions due to they are depricated,instead of it,use mysqli_* or PDO statements
And try to update your update query like
mysql_query("UPDATE Blogs SET URL = 'blogpost.php?id=$id' WHERE id=$id");
EDIT Based on your commented query try like
mysql_query("UPDATE Blogs SET URL=blogpost.php?id=$pind WHERE Content='".$cont."'")
or
mysql_query("UPDATE Blogs SET URL=blogpost.php?id=$pind WHERE Content='$cont'")
What you're actually doing wrong in the commented line when assigning to $pind is you expect the mysql_query to return your new id, but what it actually returns is a resource from which you must get the id using mysql_fetch_row or any similar function from the mysql_fetch_ family.
As for the uncommented row with WHIERE id=LAST_INSERT_ID(), it would probably work, but you're not concatenating the prefix string with your id. You should do it like this:
mysql_query("UPDATE blogs SET url = CONCAT('blogpost.php?id=', id) WHERE id = LAST_INSERT_ID()");
On the other hand I don't approve of your design of holding your urls in the database when you already have everything you need in the database (i.e. the id), so you should just prepend the "blogpost.php?id=" to the id you get when selecting that row and you're all set, this url of yours is completely unnecessary.
Oh and people are correct when they say this is deprecated, but it seems you're still learning so this is probably a little easier to grasp than the mysqli approach so you can stick with it for now and move up to mysqli once you're comfortable.
Hope that helps. Good luck.
How about this?
$pind = mysql_insert_id();
http://php.net/manual/en/function.mysql-insert-id.php
$id = mysql_insert_id();
In table id field should be auto increment field
Related
I'm very new to PHP, trying to figure things out.
I have the following php code:
$read_more = '[read more]';
$sql = "INSERT INTO database (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
The code is returning "http://www.example.com/index.php?id=0". Note that the "id" parameter is returning "0". My goal is to make it return the latest ID from the database, which is set to auto increment.
I've tried many things but nothing worked for me so far. Thanks!
EDIT: After hours of trial and error, this is how I was able to solve this problem:
//After connecting to the database
$sql = "INSERT INTO table (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
$result = mysqli_query($conn, $sql);
$id = mysqli_insert_id($conn);
Now the latest id is saved into a variable that I can use.
Try something like this instead. Check the documentation here.
// insert a datarow, primary key is auto_increment
// value is a unique key
$query = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query );
echo 'LAST_INSERT_ID: ',
mysql_query( "SELECT LAST_INSERT_ID()" ),
'<br>mysql_insert_id: ',
mysql_insert_id();
EDIT:
Im trying to submit a form with a title and body but i want the title to go to one table and body to go to another table, this in itself i can do but i need the ID generated from the title being inserted into its table to then be inserted into a field in the table the body is inserted so as to keep them linked.
What i have so far: I know its not pretty and its not safe, i will be reworking them once i learn how to do it properly.
if (#$_POST['post'])
{
$body = #$_POST['body'];
$title = #$_POST['title'];
$BoardID = #$_POST['BoardID'];
$MemberID = #$_POST['MemberID'];
$date = date("Y-m-d H:i:s");
include ('connect.php');
$insert = mysql_query("INSERT INTO threads VALUES ('','$BoardID','$title','$date','$MemberID','','')");
if($insert) {
header("location: ?p=posts&thread=$Thread_ID");
exit();
}
}
I need to somehow get $Thread_ID which has been generated in the insert and add that to a second insert for adding body to the post table, if that makes sense.
I tried getting the latest $Thread_ID and adding +1 but if multiple threads are posted at once they might get crossed over.
How would i go about fixing this?
The PHP manual tell us:
This extension Mysql is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used.
(see ref.)
You must use mysqli or PDO, to make a connection between PHP and a MySQL database.
mysqli
If you want the id of the inserted row, you can use $mysqli->insert_id (ref)
Example:
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
PDO
If you want the id of the inserted row, you can use $dbh->lastInsertId(); (ref)
And don't forget to sanatize all your inputs.
You need to execute both insert queries separately.
$insert = "INSERT INTO threads VALUES ('','$BoardID','$title','$date','$MemberID','','')";
$result = #mysql_query($insert);
$Thread_ID=#mysql_insert_id();
$insert = "INSERT INTO posts VALUES ('','$BoardID',$Thread_ID','$body','$date','$MemberID')";
$result = #mysql_query($insert);
Thanks,
I am having some problems with a script, I am basically inputting data into a MySQL table. This data will be inserted in the table as 1 row.
Upon a row of data being entered into the table I want the current/specific row currently being entered to have the column 'account_type' to be updated from its default value 'member' to 'client'.
It's a long story why I need to do it this way but I do not want to simply just enter the value 'client' it must be updated from 'member' to client.
The script I have (which is the bit at the bottom) is currently doing just this but it is affecting all rows in the table, is there a way I can add a where clause to the update to say only affect the current row being entered and do not update all other rows in the table?
<?php ob_start();
// CONNECT TO THE DATABASE
require('../../includes/_config/connection.php');
// LOAD FUNCTIONS
require('../../includes/functions.php');
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$number = $_POST['number'];
$dob = $_POST['dob'];
$accounttype = $_POST['accounttype'];
$query="INSERT INTO ptb_registrations (
username,
password,
firstname,
lastname,
email,
number,
dob,
accounttype,
date_created )
VALUES(
'".$username."',
'".$password."',
'".$firstname."',
'".$lastname."',
'".$email."',
'".$number."',
'".$dob."',
'".$accounttype."',
now()
)";
mysql_query($query) or die();
$query="INSERT INTO ptb_users (
first_name,
last_name,
email,
password )
VALUES(
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";
mysql_query($query) or dieerr();
$result = mysql_query("UPDATE ptb_users SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'");
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You can use the MySQL function LAST_INSERT_ID() to do this.
The old ext/MySQL extension exposes this functionality through mysql_insert_id(), but you can also access it directly, and more cleanly, and safely, in a query.
So you can do something like this:
$result = mysql_query("
UPDATE ptb_users
SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'
WHERE id = LAST_INSERT_ID()
");
I know you say "it's a long story..." But what you are doing makes little-to-no sense. I can only imagine you are doing this because of a trigger - and that demonstrates quite nicely why triggers are generally a bad idea ;-)
Please try and re-think your design if at all possible.
Get the inserted ID after your first query then use it in the update (assuming you have a primary key with auto-increment).
Try With WHERE Condition on unique coloumn
mysql_query("UPDATE ptb_users SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'" WHERE ptb_user.email='$email');
Im having trouble with my sql statements. I dont know what im doing wrong but it keeps adding to the database much rather than uploading
$result = mysql_query("SELECT id FROM users where fbID=$userID");
if (mysql_num_rows($result) > 0) {
mysql_query("UPDATE users
SET firstName='$firstName'
, lastName='$lastName'
, facebookURL='$link'
, birthday='$birthday'
, update='$today'
, accessToken='$accessToken'
, parentEmailOne='$parentEmailOne'
, WHERE fbID='$userID'");
} else {
mysql_query("INSERT INTO users
(fbID, firstName, lastName, facebookURL, birthday
, updated, accessToken, parentEmailOne )
VALUES ('$userId', '$firstName', '$lastName', '$link', '$birthday'
, '$today', '$accessToken', '$parentEmailOne')");
}
i see that in the first query you use $userID , while in the INSERT you are using $userId
There is an extra comma in your first (I mean the UPDATE) query:
'... $parentEmailOne', WHERE fbID='$userID'");
^
You have an extra comma in your UPDATE statement before the WHERE clause:
parentEmailOne='$parentEmailOne', WHERE fbID='$userID'"
^^^^
But, also you should make sure that your variable $userID isn't empty and echo out mysql_num_rows() to see what you're getting back from the SELECT
Also, in your SELECT you use the variable $userID but in your INSERT you are using $userId. Note the capitalization difference.
You need quotes on the first query, fbID='$userID'
Also, you dont need this , before where, on the second SQL
And last, you use userID on the first reference, and userId on the last
Do the names contain any apostrophes?
You'll want to be sure to use mysql_real_escape_string
Are you saying it inserts rather than updating? In other words, it's failing to find existing records that you expect it to find?
I recommend that instead of doing "update if the record exists, otherwise insert" logic yourself, you look into MySQL's built-in functionality.
update is keyword and you must use from delimiter.
and one comma in first query is extra
$result = mysql_query("SELECT `id` FROM `users` where `fbID`=$userID");
if (mysql_num_rows($result) > 0) {
mysql_query("UPDATE `users` SET `firstName`='$firstName', `lastName`='$lastName', `facebookURL`='$link', `birthday`='$birthday', `update`='$today', `accessToken`='$accessToken', `parentEmailOne`='$parentEmailOne' WHERE `fbID`='$userID'");
} else {
mysql_query("INSERT INTO `users` (`fbID`, `firstName`, `lastName`, `facebookURL`, `birthday`, `updated`, `accessToken`, `parentEmailOne` ) VALUES ('$userId', '$firstName', '$lastName', '$link', '$birthday', '$today', '$accessToken', '$parentEmailOne')");
}
this is standard code
if the userID column is a varchar, you should quote the $userID variable in your first query
PLease note I am a beginner.
My situation is thus:
I am trying to run multiple queries, off the back of a dynamic form. So the data is going to end up in two different tables.
I am currently successfully storing in to my item_bank, which has an auto_increment itemId.
I then want to grab the ItemId just created on that last query and insert it into my next query of which I am also inserting an array. (I hope you can follow this)
first off, is it even possible for me to run multiple queries like this on a single page?
Below is my attempt at the queries. Currently the first query works, however I cannot get the ItemId generated from that query.
$answers is an array.
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$query = "INSERT INTO answers_tb (item_id, text_value)VALUES('$itemid',' . implode(',', $answers) . ')";
mysql_query($query) or die(mysql_error());
this is the error i get now: "Column count doesn't match value count at row 1"
To get the ID generated by an auto-increment field in PHP/MySQL just use the mysql_insert_id() function.
Edit:
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$answers = mysql_real_escape_string(implode(',', $answers));
$query = "INSERT INTO answers_tb (item_id, text_value) VALUES('$itemid','$answers')";
mysql_query($query) or die(mysql_error());
Have a look at mysql_insert_id():
// store item structure info into item_bank_tb
mysql_query($query);
$itemid = mysql_insert_id();
// now store different answers