i would like to insert values into my combined primary key. However, i only get the erorr message Duplicate entry '1-16' for key 'PRIMARY'
I am sure there is no connection problems as previous SELECT querys have worked, and everything else on the site is running. Below is my code for the segmet. I am very grateful for all help, but as i am a beginner i would really apreciate straightfoward and easy answers:) Thanks in advance!
<form method="post">
<select name="sport_id">
<?php
$sql= "SELECT * FROM sport";
$resultat= $kobling->query($sql);
while ($rad = $resultat->fetch_assoc()) {
$sport_id=$rad["sport_id"];
$sportName=$rad["name"];
echo "<option value='$sport_id'> $sportName </option>";
}
?>
</select>
<select name="person_id">
<?php
$sql= "SELECT person_id, fname, lname FROM person";
$resultat= $kobling->query($sql);
while ($rad= $resultat->fetch_assoc()) {
$person_id=$rad["person_id"];
$fname= $rad["fname"];
$lname =$rad["lname"];
$navn= $fname. " ". $lname;
echo "<option value='$person_id'> $navn </option>";
// code...
}
?>
</select>
Året du startet:
<input type="number" name="startyear" value="">
<input type="submit" name="leggtil3" value="Legg til">
</form>
<?php
if (isset($_POST["leggtil3"])) {
$person_id=$_POST["person_id"];
$sport_id = $_POST["sport_id"];
$startyear=$_POST["startyear"];
$sql= "INSERT INTO personsport (sport_id, person_id, startyear) values ('$sport_id', '$person_id', '$startyear')";
if ($kobling->query($sql)) {
echo "koblingen $sql ble gjennomført";
}
else {
echo "det var et problem med $sql ($kobling->error)";
}
}
?>
Your INSERT is attempting to assign a non-unique combination for PRIMARY fields. Auto Increment can mess up; ensure the next number in sequence is not taken.
Mysql Docs
Updating an existing AUTO_INCREMENT column value in an InnoDB table
does not reset the AUTO_INCREMENT sequence as it does for MyISAM and
NDB tables.
(It looks like your just entering the same person and sport twice. Those fields must be unique in combination due to your index.)
The primary keys 1 - 16 are already assigned in the database. Check the database to be sure your next value for auto increment does not hold any of these values.
Related
I am trying to get the last Employee ID from my Sqli table, increment the id retrieved from the table and insert the new value into the table along with the new record.
The code is not working as the table is not getting updated.
<form method="POST">
<input type="text" name="brn" placeholder="Branch"/>
<input type="text" name="nam" placeholder="Enter Name"/>
<input type="submit" name="insert">
<?php
$db=mysqli_connect("localhost","root","","test");
session_start();
if(isset($_POST['insert']))
{
$brn = $_POST['brn'];
$nam = $_POST['nam'];
$qry = "SELECT * FROM emp";
$result=mysqli_query($db,$qry);
$row = mysqli_fetch_array($result);
$empid= $row["empid"];
$empid++;
$query = "INSERT INTO `emp`(`brn`,`nam`,'empid') VALUES ('$brn','$nam','$empid')";
mysqli_query($db,$query);
mysqli_close($db);
}
?>
</form>
You need some changes in your code.
You are selecting the first "EmpId" instead of the last one and if you are having the column empid as primary key, it will show the error of primary key violation.
Therefore change your query to somewhat this:
$qry = "SELECT * FROM emp order by empid desc limit 1";
It will return one row.
And, if you just need the last empid then i would suggest you to go with only:
$qry = "SELECT empid FROM emp order by empid limit 1";
This is more resource effective query.
****Happy Coding.****
you can try this. I hope it will help you.
$sql = "INSERT INTO `emp`(`brn`,`nam`,'empid') VALUES ('$brn','$nam','$empid')";
if(mysqli_query($db, $sql)){
$last_id = mysqli_insert_id($db);
echo "Records inserted successfully. Last inserted ID is: " . $last_id;
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
I have just figured out how to populate a datalist element from mysql. I need to get the associated ID that corresponds to the selected value to submit to another page. I can submit the value, but I need the ID. I hope it is a simple syntax error, but I can't figure it out.
Thanks in advnace.
<?php
require 'connect_mysqli.php';
$sql = "SELECT street FROM streets";
$result = mysqli_query($con, $sql) or die ("Error " . mysqli_error($con));
?>
<form action="new.php" name="test" method = "post">
<datalist id="street" name="streets">
<?php while($row = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row['street']; ?>"><?php echo $row['street_id']; ?></option>
<?php
}
?>
</datalist>
<input type="text" name="street" id="test" autocomplete="off" list="street">
<input type="submit" value="Submit">
<?php
mysqli_close($con);
?>
Also I think you are doing wrong to submit value of street. Change it to this
<option value="<?php echo $row['street_id']; ?>"><?php echo $row['street']; ?></option>
It will display street name and submit street id And get value like this
$_post["streets"];// I haven't used datalist but if works it would be this
Look at your query:
$sql = "SELECT street FROM streets";
"I hope it is a simple syntax error"
You didn't make a syntax "error", you just didn't select the street_id column in your query, that's why it's not showing in the dropdown, in regards to $row['street_id'].
You need to add it in your query:
$sql = "SELECT street, street_id FROM streets";
N.B.: Column selection are separated by commas. You can further add to the query if you wish, but make sure there isn't a trailing comma following the last column chosen.
I.e: This would FAIL:
$sql = "SELECT street, street_id, col3, FROM streets";
However, $row['street_id'] and $row['street_ID'] are two different animals altogether here. So, make sure that that is the letter-case used. They are case-sensitive when it comes to looping over column names, and that would trigger an error when checking for them, being something to the effect of an unexisting column.
Sidenote:
I didn't see a closing </form> tag in your posted code. Make sure it's part of your real code.
Reference:
http://dev.mysql.com/doc/refman/5.7/en/select.html
You just forgot to include the street_id column in the columns you are selecting from the streets table.
Change this line:
$sql = "SELECT street FROM streets";
to this line:
$sql = "SELECT street, street_id FROM streets";
I have the user select a member ID, but I want it to delete the corresponding event ID (PK) so the row is just deleted. Can you suggest a simple and effective way of doing this? This is the code I am working on FYI.
Front end.
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
Select member ID to <b> remove total and comment. </b>: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<input type="submit" value=">!DELETE!<" />
</form>
<?php
}
else
{
$mid = $_POST['meid'];
$db1 = new dbme();
$db1->openDB();
$numofrows = $db1->delete_total($meid);//basically kill off the entire row
echo "Success. Number of rows affected:
<strong>{$numofrows}<strong>";
Back end method
function delete_total($mid, $meid) {
$sql = "DELETE FROM memberevent WHERE mid = $mid"; // This is the bit I am head scratching, might there be a way to use mid to identify the corresponding PK (meid) to delete so the entire row is killed?
$result = mysqli_query($this->conn, $sql);
if ($result) {
$numofrows = mysqli_affected_rows($this->conn);
return $numofrows;
}
else
$this->error_msg = "could not connect for some wierd reason";
return false ;
}
P.S I am aware it cannot work in its current form.
Here's the memberevent table structure.
meid (PK auto incr INT)
mid (int)
total (varchar)
comments (varchar)
ename (varchar)
We are having troubles with our php session.
Trying to add a patient to a database, linked to the doctor that is curing the patient.
We have a select from the existing doctors in the database. They show up in the dropdown list.
But when we are trying to send the selected doctor to the database (the php session), there is no addition to the database. All the other inputs (patient name, patient birth date, etc) are put in the database, except the data from the dropdown list.
Add_patient.php
Doctor:<br>
<select name="doctor">
<option value="">--Select--</option>
<?php
$config = parse_ini_file("divkey.ini.php", true);
include("connect/connect_mysql.php");
$opdracht = "SELECT * FROM gebruiker ORDER BY id";
$resultaat = mysql_query($opdracht);
while ($rij = mysql_fetch_array($resultaat)) {
$id = $rij['id'];
$name = $rij['name'];
$fname = $rij['fname'];
?>
<option value ="<?php $id;?>"><?php echo"$name $fname" ?></option>
<?php
} ?>
</select>
Session_add.php
$doctor = $_POST['doctor'];
# query
Our query from session_add.php works. Just the not for the $_POST['doctor'].
# query
$opdracht = "INSERT INTO patient ( `name`, `fname`, `geslacht`, `doctor`, `straatnaam`, `huisnummer`, `postcode`, `gemeente`, `telefoonnummer`, `patientnummer`, `land`, `bloedgroep`, `gsmnummer`, `geboortedatum`, `geboorteplaats`, `taal`, `nationaliteit`, `rijksregisternummer`, `huisarts` )
VALUES ('".$name."', '".$fname."', '".$geslacht."', '".$doctor."','".$straatnaam."' ,'".$huisnummer."' , '".$postcode."' , '".$gemeente."', '".$telefoonnummer."',
'".$patientnummer."','".$land."', '".$bloedgroep."', '".$gsmnummer."', '".$geboortedatum."', '".$geboorteplaats."', '".$taal."', '".$nationaliteit."','".$rijksregisternummer."', '".$huisarts."')";
# other values are not important, it's in Dutch and these values are sent to the database
# doing query
$result = mysql_query($opdracht) or die(mysql_error());
# we use or die(mysql_error())
The query is executed, a 0 (zero) is added to the database instead of the selected doctor.
<option value ="<?php echo $id;?>"><?php echo $name.$fname; ?></option>
Try this.
We found the problem, it was in the sql query. With var_dump($_POST)
I checked the values that were sent to the session, these were the right ones.
In the SQL query, there was '".$doctor."'
This was wrong, it should be '.$doctor.' (recognised as id)
Thanks for the help!
I want to build a form to change the data in MySQL table. Firstly, I list all the data in the adminindex.php page. Then, I create a button to open the selected data in a form. I've done assigning the form fields to the main (pk) MySQL table. My problem started there when I need to fetch the foreign table data as the table contains many foreign data. As you guys know, a class may have many students, I have created the fields for class data, now the problem is in students data. Do I have to create many fields to fetch the data from MySQL foreign tables? If yes, could you guys guid me the code steps ? Thank you very much. Really appreciate your help :D
These are my steps:
Firstly I echo the rows, then I codes the form actions. Then, in adminpost.php, I create variables, link the fields and use UPDATE MYSQL to update the data in tables. I've succeeded in updating the primary table data but I'm stuck in foreign key data. Thanks :D
Have 2 pages. Display data in a form in first one and have update in the second. Here is a code for doing it one by one, you can build on it for multiple rows at a time if you want to.
edit.php
<?php
mysql_connect('ip', 'username', 'password') or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query = mysql_query("SELECT * FROM table1 where order by question_id limit 1") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$id = $row['id'];
$value1= $row['value1'];
$value2= $row['value2'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?php echo $id;?>">
Value1: <input type="text" name="value1" value="<?php echo $value1;?>">
<br>
Value2: <input type="text" name="value2" value="<?php echo $value2?>">
<input type="Submit" value="Change">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
update.php
<?php
mysql_connect('ip', 'username', 'password') or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$id = mysql_real_escape_string($_POST["ID"]);
$value1 = mysql_real_escape_string($_POST["value1"]);
$value2 = mysql_real_escape_string($_POST["value2"]);
$query="UPDATE table1 SET value1 = '.$value1.', value2 = '.$value2.' WHERE id='$id'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>($id) Record Updated<p>";
}else{
echo "<p>($id) Not Updated<p>";
}
?>
Next
Might help to put your actual code up, but as i understand you are just wanting to edit the data that is already in your table? If thats the case :
//Connect to SQL DB
$dbcnx = #mysql_connect("localhost", "root", "password");
//Select DB
mysql_select_db("database_name", $dbcnx);
//Query DB
$sql = update table_name set column_name = "$variable" where column = "your_criteria";
#mysql_query($sql)
That will connect you to your SQL DB and update the records for you, hope thats what you needed