Click here to Skip to main content
15,445,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have a problem, that my code runs correctly, insert data to database, but the success message after lastInsertId is not working.

Please help.

What I have tried:

PHP
if(isset($_POST['submit']))
	{
		$class=$_POST['class'];
		$subject=$_POST['subject'];
		$lesson=$_POST['lesson'];
		$topic=$_POST['topic'];
      	$date = date('Y-m-d');
		$teacherid = $_SESSION['teacherid'];
		$teachername = $_SESSION['fullname'];
		$sql = "INSERT INTO homework (class,subject,lesson,topic,`date`,teacherid,teachername) VALUES(:class,:subject,:lesson,:topic,:date2,:teacherid,:teachername)";
		$query=$conn->prepare($sql);
        $query->bindparam(':class',$class,PDO::PARAM_STR);
        $query->bindparam(':subject',$subject,PDO::PARAM_STR);
        $query->bindparam(':lesson',$lesson,PDO::PARAM_STR);
        $query->bindparam(':topic',$topic,PDO::PARAM_STR);
      	$query->bindparam(':date2',$date,PDO::PARAM_STR);
        $query->bindparam(':teacherid',$teacherid,PDO::PARAM_INT);
      	$query->bindparam(':teachername',$teachername,PDO::PARAM_STR);
		$query->execute();
		$lastInsertId = $conn->lastInsertId();
		if($lastInsertId)
		{
			echo "<script language='text/javascript'>alert('Home work submitted successfully');</script>";
			echo "<script type='text/javascript'> document.location = 'index.php'; </script>";
		}
	}
Posted
Updated 15-Oct-20 10:17am
Comments
Richard MacCutchan 15-Oct-20 10:35am    
What is the value returned by $conn->lastInsertId() and put in $lastInsertId when this code runs?
nyt1972 15-Oct-20 11:44am     CRLF
I tried this and its not executing even. $lastInsertId = $conn->lastInsertId(); echo "". $lastInsertId ."";
Richard MacCutchan 15-Oct-20 11:54am    
That does not sound correct. You will need to do some debugging to find out what is happening.
nyt1972 15-Oct-20 12:02pm    
In debug its executing the lines, but not alerting the message.

1 solution

lastInsertId() is a method that applies to a PDO object, not a connection...
check the documentation!

:)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900