Adding records in multiple tables PHP MYSQL - php

I have two tables, users and comments. I need to add firstname and lastname to users and the comments to the comments table with the user id as a foreign key in comments. I am using phpmyadmin to do the add the foreign key constrain and relationships.
This is my html form:
<form action="dbconnect.php" method="post">
Firstname: <input type="text" name="firstname"><br />
Lastname: <input type="text" name="lastname"><br />
Comments: <textarea cols="30" rows="5" name="comments"></textarea><br />
<input type="submit">
</form>
This is my php insert code:
mysql_select_db("test", $db_server);
$sql="INSERT INTO users (Firstname, Lastname)
VALUES
('$_POST[firstname]','$_POST[lastname]')";
$sql="INSERT INTO comments (Comment)
VALUES
('$_POST[comments]')";
if (!mysql_query($sql,$db_server))
{
die('Error' . mysql_error());
}
echo "1 record added" ;
mysql_close($db_server);
and this is the error i'm getting:
Error: Cannot add or update a child row: a foreign key constraint fails
(test.comments, CONSTRAINT comments_ibfk_2 FOREIGN KEY
(useridfk) REFERENCES users (id) ON DELETE CASCADE ON UPDATE
CASCADE)
I am new to php and phpmyadmin so any help is appreciated.

First of all, you need to run the INSERT query on the users table so the user record is created.
mysql_select_db("test", $db_server);
$sql="INSERT INTO users (Firstname, Lastname)
VALUES
('$_POST[firstname]','$_POST[lastname]')";
mysql_query($sql);
if (!mysql_query($sql,$db_server))
{
die('Error' . mysql_error());
}
echo "1 record added" ;
You then need to retrieve the id of the newly created record on the users table
$newIdQuery = mysql_query("SELECT LAST_INSERT_ID() AS userId FROM users");
$newId = mysql_fetch_assoc($newIdQuery);
Then you can use that userId to add the comments, with the user id foriegn key properly populated.
Note: When building MySQL queries using the mysql_* functions, if you wrap a php variable in { } it will insert the value of the php variable into the SQL statement.
$sql="INSERT INTO comments (id, Comment)
VALUES
({$newId["userId"]}, '$_POST[comments]')";
if (!mysql_query($sql,$db_server))
{
die('Error' . mysql_error());
}
echo "1 record added" ;
mysql_close($db_server);

Related

How to write multiple insert in multiple tables using the same form PHP

I have a problem with inserting data into two different tables: When a new member is created, it will be insert into member and grade tables after getting the id course from course table. I used INSERT for both of them at the same time with a multi query function but it doesn't work.
Can you help me please?
The form:
<form>
<input type="text" name='m_fName'>
<input type="text" name='m_lName'>
<input type="text" name ='m_nId'>
</form>
Php
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId)
VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');
INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
mysqli_multi_query($conn,$sql);
$id = $re['c_id'];
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$sql .="INSERT INTO grade(c_id,m_nId) VALUES( '$id','$_POST[m_nId]')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Hope this will help. but try to first validate the posted data. check if isset .you did not show in the are you using post and the page you are posting your data
Answer above is the correct one, alternative way is the code below
$id = $re['c_id']; //to get id of course that I want to insert
$sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
$act = mysqli_query($conn,$sql);
if($act) {
$sql2 = "INSERT INTO grade(c_id,m_nId)
VALUES( '$id','$_POST[m_nId]')";
$act2 = mysqli_query($conn,$sql2);
}

How to insert values in database if it set foreign key?

<?php
if(isset($_GET['email']) && !empty($_GET['email']))
{
$email = mysql_real_escape_string($_GET['email']);
$sml="UPDATE USERS SET password=$_POST[password] where email='$email' ";
$account=mysql_query("INSERT INTO ACCOUNT(email) SELECT email from USERS WHERE email='$email' ") or die('Error:' .mysql_error());
if (mysql_query($sml,$con))
{
header('Location: ../home.html');
}
else{
die('Eror: ' . mysql_error());
}
}
else
{die('Eror: ' . mysql_error());}
mysql_close($con);
?>
How to insert email in account table its an foreign key for the account table.
I want to insert same email value to the account table for the other table reference.
You have to add user/s first. You can't add a record into Accounts table if you don't have a matching record in the parent(Users) table.
That is how foreign key constraint works. For example if you have a record in Users table with user_id = 1, you are only allowed to have records with user_id = 1 in the Accounts table. And so on...
Hint 1:
Try not to put $_POST['key'] directly into query because that makes it vulnerable to sql injection.
Hint 2:
Use exit after header function.

How can I insert the last Id into the child table :

I am trying to insert into two tables the mother table and the child table : but the mother table gets the data and the child table does not : I get the error
Cannot add or update a child row: a foreign key constraint fails (portfolio.players, CONSTRAINT players_ibfk_1 FOREIGN KEY (user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE)
And bellow is my code :
$query="INSERT INTO users(email,date)
VALUES('$email','$date')";
$user_result = mysql_query($query);
/*last inserted Id */
$id_last = ("SELECT LAST_INSERT_ID()");
$res = mysql_query($id_last);
$last_id = mysql_fetch_array($res);
/*last inserted Id ends*/
/*insert query */
$sql="INSERT INTO
players(name, surname, position, contact_number, email, username, password, date, user_id)
VALUES('$name ','$surname','$position','$contact_number','$email','$username','$password', '$date', '$last_id')";
$result = mysql_query($sql)or die (mysql_error());
/*if something goes wrong then tell the user*/
if($result){
echo "Player Successfully added</br>";
}
else {
echo "We are sorry no player inserted ";
}
$last_id = mysql_fetch_array($res);
mysql_fetch_array returns array, to get actual id you should use $last_id[0]. Also there is function for that: mysql_insert_id. While looking on linked manual page, please pay attention to big red frame, and continue developing with either mysqli or PDO.

allow duplicate entries for all posts in php

How do i allow duplicate entries in my php file from this file ... i have the html file which is a form to track radios for a company. I have text boxes and radio buttons and all the fields need to be able to have duplicate entries except for the serial number field. i keep getting and error saying i cannot have duplicate entries.
<?php
$con = mysql_connect("localhost","Jason","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$sql="INSERT INTO test (
firstname,
lastname,
department,
radiomodel,
serialnumber,
issuedate
)
VALUES(
'$_POST[firstname]',
'$_POST[lastname]',
'$_POST[department]',
'$_POST[radiomodel]',
'$_POST[serialnumber]',
'$_POST[issuedate]'
)";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
header( "refresh:150;url=testinput.php" );
?>
Your serialnumber is a primary key and thus you can not have duplicate values.
You should remove the primary key from the serialnumber field and add in a new id column to put the primary key on this or use multiple columns together as the key, for example use firstname, lastname and date and serialnumber as the key.
Really you should split this off into multiple tables though.

PHP Cannot Add Or Update Child Field - Foreign Key Error

I am getting an error when trying to insert some values into a MySQL Database - My page currently reads the value 'EventID' which is passed through the URL and allows me to Add Results based on that EventID. I currently have a Drop down box which is populated by the Members within the members table.
I get this horrid error:
Cannot add or update a child row: a foreign key constraint fails (clubresults.results, CONSTRAINT ResultEvent FOREIGN KEY (EventID) REFERENCES events (EventID) ON DELETE CASCADE)
I am not able to change the table structure so any help would be great appreciated.
Note - I'm currently having it echo the SQL to find the error as to why it won't insert.
<?php
error_reporting (E_ALL ^ E_NOTICE);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("clubresults", $con);
// Get id from URL
$id = mysql_real_escape_string($_GET['EventID']);
// If id is number
if ($id > 0)
{
// Get record from database
$sql = "
SELECT EventID
FROM results
WHERE EventID = " . $id;
$result = mysql_query($sql);
}
if (isset($_POST['submit'])) {
$sql="INSERT INTO results (MemberID, Score, Place)
VALUES
('".$_POST['student']."', '".$_POST['Score']."', '".$_POST['Place']."')";
$add_event = mysql_query($sql) or die(mysql_error());;
echo $add_event;
}
HTML Form -
$_SERVER['PHP_SELF']?>" method="post">
<table border="0"><p>
<tr><td colspan=2></td></tr>
<tr><td>Member Name: </td><td>
<?php
$query="SELECT * FROM members";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);
echo "<select name=student value=''>Student Name</option>";
// printing the list box select command
while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value='$nt[MemberID]'>$nt[Firstname] $nt[Surname]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
?>
<tr><td>Score:</td><td>
<input type="text" name="Score" maxlength="10">
<tr><td>Place:</td><td>
<input type="text" name="Place" maxlength="10">
</td></tr>
<tr><th colspan=2><input type="submit" name="submit"
value="Add Result"> </th></tr> </table>
</form>
You have to insert the EventID into your results record:
$sql="INSERT INTO results (MemberID, Score, Place, EventID) VALUES (?, ?, ?, ?)";
Note I have used ? placeholders in place of your $_POST variables (which left you vulnerable to SQL injection).
You should use instead prepared statements into which you pass your variables as parameters that do not get evaluated for SQL, but they are not available in the ancient MySQL extension that you're using (which the community has begun deprecating anyway, so you really should stop writing new code with it); use instead either the improved MySQLi extension or the PDO abstraction layer.

Categories