EDIT: Question edited to be exact after Marcus reply
I am trying to practice library management and my page is for order where a book can be ordered as many time but same book should not be selected in two different selects on one page. On order page, I have multiple select dropdowns for book values coming from same database:
<select name="user">
<option value="1">Tony</option>
<option value="2">Gary</option>
<option value="3">Martin</option>
<option value="4">Austin</option>
<option value="5">Mark</option>
</select>
<select name="book[]">
<option value="1">Math</option>
<option value="2">Geography</option>
<option value="3">Science</option>
<option value="4">Spanish</option>
<option value="5">English</option>
</select>
<select name="book[]">
<option value="1">Math</option>
<option value="2">Geography</option>
<option value="3">Science</option>
<option value="4">Spanish</option>
<option value="5">English</option>
</select>
<select name="book[]">
<option value="1">Math</option>
<option value="2">Geography</option>
<option value="3">Science</option>
<option value="4">Spanish</option>
<option value="5">English</option>
</select>
And adding them in database table which has ID as auto increment for record and bookID to store book id. I am doing it with:
$userID = $_POST['user'];
foreach($_POST['book'] as $key=>$item_eid){
$bookID = intval($_POST['book'][$key]);
mysql_query ("Insert INTO user_books (bookID, userID) values ('$bookID', '$userID' )") or die(mysql_error());
}
I dont want to have two record of same book ID. In short, I want to avoid duplicate entries on bookID. I have tried "INSERT IGNORE INTO" but it did not work. Also, I want to show an error if duplicate entries are selected instead of just ignoring. Any thoughts on it?
Edit: Table structure:
CREATE TABLE IF NOT EXISTS user_books
(
ID int(11) NOT NULL AUTO_INCREMENT,
bookID int(11) NOT NULL,
userID int(11) NOT NULL,
added timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
)
ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;
The column needs to be UNIQUE. Right now there is no constraint on the column which is allowing it to have duplicate values. Change the column to UNIQUE:
ALTER TABLE user_books ADD UNIQUE (bookID);
This query will fail, however, if you already have duplicate values in the bookID column. If you don't care about the (automatic) removal of duplicate entries, use the following query instead:
ALTER IGNORE TABLE user_books ADD UNIQUE (bookID);
This will keep the first found entry of any duplicates, and delete the rest, ie. Imagine having 5 entries with bookID 100. The aforementioned query will keep the first entry with bookID 100, and delete the remaining 4 automatically.
Then you can use INSERT IGNORE INTO thereafter.
Related
I have two tables: TEMA e SOTTOTEMA.
In TEMA I have, as primary key, IDtema which is auto-increment.
I want it to be foreign key in the sottotema table and I wrote, in phpmyadmin, where I have my db,
ALTER TABLE sottotema ADD FOREIGN KEY (IDtema) REFERENCES tema (IDtema)
It doesn't give me errors, but the foreign key doesn't work.
I have predefined themes in a select option, and depending on the theme you choose, you can insert a sub-theme yourself.
<select id = "tema" name = "tema">
<option hidden></option>
<option value = "Animali"> Animali</option>
<option value = "Cucina"> Cucina </option>
<option value = "Sport"> Sport </option>
<option value = "Musica"> Musica </option>
<option value = "Cinema"> Cinema </option>
<option value = "Letteratura"> Letteratura </option>
</select></br>
<div id = "sottotema" style = "display:none">
<p id = "titolosottotema"> Sottotema </p>
<input type = "text" placeholder="Scrivi un sottotema" id = "st" name = "st"/>
</div>
All this obviously is inside a FORM and everything works, except for inserting the IDtema as a foreign key, in the sottotema table.
I report only the data entry queries in the db, but in my php code there is something else written, including the connection to the db obviously
<?php
$sottotema = $_POST['st'];
$query = "INSERT INTO sottotemi (nomeSottotema) VALUES ('$sottotema')";
$result = mysqli_query($mysqli, $query);
if (!$result){
echo "errore 1";
} else {
$query2 = "INSERT INTO blog (titoloBlog,nomeSottotema,nomeUtente,sfondo, font, colorefont) VALUES ('$titoloblog','$sottotema',(SELECT nomeUtente FROM utentiregistrati WHERE nomeUtente = '$nomeutente'),'$sfondo','$font','$colore');";
$result2 = mysqli_query($mysqli, $query2);
if(!$result2){
echo 'errore 2';
}
?>
In the db I have already entered my predefined themes, so the idtema, primary key, is already associated with a specific theme (eg 1 - Animali, etc.).
Please help me I'm desperate !!!!!
For the foreign key to work you need to specify the foreign table identifier in the INSERT operation, otherwise the row would be orphan form the start. Instead of INSERT INTO sottotemi (nomeSottotema) VALUES ('$sottotema') you'll need to find identifier (IDtema) to the foreign table (tema) and also provide it in the INSERT operation as follows (NOTE this is a different format of the INSERT statement that consumes the results of a SELECT statement instead of using the VALUES() version):
INSERT INTO sottotemi
(nomeSottotema, IDtema)
SELECT
'$sottotema', T.IDtema
FROM tema AS T
WHERE T.nome = '$tema'
How I can insert values from database to <select> -> <option> in HTML?
Example:
I have table with ID_class and name of class. And I would like to user can choose <option> with value name of class.
<select>
<option>VALUE FROM TABLE</option>
...
</select>
I work with PDO and jQuery.
It's not obvious where you're getting stuck, but here are some snippets to help out.
First of all, your select needs a name and options need a value, so that the selected value can be accessed on the server side.
<select name='chooser'>
<option value='name-1'>...</option>
<option value='name-2'>...</option>
</select>
On the server side, your query should look something like this using PDO:
$insertData = $con->prepare('
INSERT INTO your_table
VALUES(
DEFAULT,
:name,
)
');
// the value of $_POST['chooser'] here is the value of the selected option (e.g. "name-2")
$insertData->bindValue('name', $_POST['chooser'], PDO::PARAM_STR);
$insertData->execute();
I'm having a problem with a MySQL query that uses inner and left joins. The problem is that, where the foreign key in the primary table is blank in the case of a NULL-permitted field, the query doesn't read all the fields in the primary table.
My task is to organize a list of recordings with MySQL, some of which are live recordings while others are studio recordings. For the purposes of this question, I'm simplifying the table structure as follows:
table name: recordings
fields:
recording_id INT AUTO-INCREMENT
recording_name VARCHAR NOT NULL
artist_id INT NOT NULL FOREIGN KEY
event_id INT NULL FOREIGN KEY
table name: artists
fields:
artist_id INT AUTO-INCREMENT
artist_name VARCHAR NOT NULL
table name: events
fields:
event_id INT AUTO-INCREMENT
event VARCHAR NOT NULL
venue_id INT NOT NULL FOREIGN KEY
table_name: venues
fields:
venue_id INT AUTO-INCREMENT
venue_name VARCHAR NOT NULL
address VARCHAR NOT NULL
Where a recording was done live, I want the option to give details of the event where the recording was done, and if it was a studio recording, I leave the event field blank. In other words, in the recordings table event_id is an optional field, but artist_id is always required.
To edit an existing record in the recordings table, I have a form with three fields (again simplified):
<form>
<input name="recording_name" type="text" value="<?php $recording_name ?>" />
<select name="artist_id">
<option>Select option</option>
<option <?php $selected ?> value="1">Artist 1</option>
etc.
</select>
<select name="event_id">
<option>Select option</option>
<option <?php $selected ?> value="1">Venue 1</option>
etc.
</select>
</form>
I use the $selected variable to display the option corresponding with the existing value pulled from the database in the form's dropdown list, like so:
$selected = ($existing_value == $option_id ? 'selected="selected" : '');
Now, to get the existing values of the form I have the following SQL query:
$recording_sql =
'SELECT * FROM recordings
INNER JOIN artists ON recordings.artist_id = artists.artist_id
LEFT JOIN events ON recordings.event_id = events.event_id
LEFT JOIN venues ON events.venue_id = venues.venue_id'
Then, to populate the two dropdowns:
$artist_sql =
'SELECT * FROM artists'
$event_sql =
SELECT * FROM events
INNER JOIN venues ON events.venue_id = venues.venue_id
My PHP code looks something like this:
function buildForm($result){
$data = $result->fetch_array($MYSQLI_ASSOC))
$form = '<input name="recording_id" type="hidden" value="'.$data['recording_id'].'" />';
$form .='<input name="recording_name" type="text" value="'.$data['recording_name'].'" />';
$form .= buildSelectBox('artists', $data['artist_id']);
$form .= buildSelectBox('events', $data['event_id']);
return $form;
}
function buildSelectBox($table, $existing_id = NULL){
//run SQL to pull data from relevant table (i.e. $artist_sql, or $event_sql which includes join to 'venues')
//Loop through $mysqli_result to build each option
while(etc....){
$selected = ($existing_id == $option_id ? 'selected="selected" : '');
$options_list .= '<option'.$selected.'value="'.$id.'">'.$artist_name.'</option>';
}
return $options_list;
}
This works fine if both foreign keys have values. However, when the event_id field is blank in recordings, it doesn't read the other foreign key either. It reads the text field, recording_name, fine though. In other words, the result set I get for $recordings_sql contains only the value of the recording_name field, while both foreign keys are returned blank, even though one is not blank. I've tried all the join permutations (left, inner, right) in different combinations, but none of them give the desired result.
I'm stumped! Thank you in advance for any help!
I spent most of yesterday trying to reproduce the problem with a simplified version of my application, and eventually I did. It turns out that the first foreign key (artist_id in my simplified example), was repeated in another table lower down in a series of joins that start with the second foreign key (event_id in my simplified example). So, my guess is that, if 'event_id' is null, 'artist_id' gets overwritten by a null value because the query will return empty values for everything after 'event_id' if it is empty. So, the problem isn't with how LEFT JOIN works, but rather with the repetition of the first foreign key in a subsidiary table that depends on a second foreign key that is allowed to be null. I evidently need to revisit my table structure...
Many thanks for all the suggestions!
I have a select box which have multiple item select facility
<select multiple="" class="form-control" name="mul[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Here select box item generate dynamically from another table.so item amount can be increase or decrease.for this reason i cant use set data type.
Now i want to insert selected value in my database table.
MY table look like
id name item
1 first mul[] value
2 second mul[] value
I want to insert selected item in DB Table column named item.
Also i want to retrieve every row data.
view like
id name item
1 first 1,2,3
2 second 2,4
I tried
$select_value=$_POST['mul'];
$sql="insert into mytable (`id`, `name`, `item`) VALUES (null, 'Hallo',$select_value)";
Use php impload function.
http://www.w3schools.com/php/showphp.asp?filename=demo_func_string_implode
In your case it will b like
$select_value=implode(", ", $_POST['mul']);
$sql="insert into mytable (`id`, `name`, `item`) VALUES (null, 'Hallo',$select_value)";
Then insert it.. :)
Try this.. i hope it helps you
This will automatically changes array to string, with comma:
$select_value = join($_POST['mul'],',');
'implode' of php is the solution:
echo implode(",",$_POST['mul']);//here $_POST['mul'] = ['1','2','3']
It will output string "1,2,3", insert it your table.
Here is more info about implode implode
Also ,if you want to retrieve records from DB table using your option values then FIND_IN_SET() function of sql will be useful , the query will be :
SELECT * FROM mytable WHERE FIND_IN_SET('option_value',`item`) <>0
I'm busy trying to create a website for my football team. The thing I'm having problems with is creating a web form with drop down boxes to select and insert the match data. I'm already able to add a match in phpmyadmin where I can just select team_home and team_away, so the relational database seems to work.
I've got the following 2 tables:
Teams
id (pk - ai)
name
Matches
id (pk - ai)
date
team_home (foreign key -> table teams field name)
team_away (foreign key -> table teams field name)
score_home
score_away
So how can I make a web form with drop down boxes so I can add matches into my database?
UPDATE:
I've got the form working with drop down boxes, but I'm getting the following error when I'm submitting the form:
Error: Cannot add or update a child row: a foreign key constraint fails (roflz.matches, CONSTRAINT matches_ibfk_1 FOREIGN KEY (team_home) REFERENCES teams (name))
I've posted my submit form code and insertmatch.php code
Submit form code
$sql="SELECT id, name FROM Teams";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["id"];
$name=$row["name"];
$optionshometeam.="<OPTION VALUE=\"$id\">".$name;
$optionsawayteam.="<OPTION VALUE=\"$id\">".$name;
}
?>
<form action="insertmatch.php" method="post">
<SELECT NAME=Teams>
<OPTION VALUE=0>Home Team
<?=$optionshometeam?>
</SELECT>
<SELECT NAME=Teams>
<OPTION VALUE=0>Away team
<?=$optionsawayteam?>
</SELECT>
Score Home team: <input type="text" name="score_home" />
Score Away team: <input type="text" name="score_away" />
Match Date: <input type="text" name="score_away" />
<input type="submit" />
</form>
insertmatch.php code
mysql_select_db("roflz", $con);
$sql="INSERT INTO matches (team_home, team_away, score_home, score_away, date)
VALUES
('$_POST[team_home]','
$_POST[team_away]','
$_POST[score_home]','
$_POST[score_away]'
$_POST[date]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Match added";
mysql_close($con);
?>
So what's causing this error?
Error: Cannot add or update a child row: a foreign key constraint fails (roflz.matches, CONSTRAINT matches_ibfk_1 FOREIGN KEY (team_home) REFERENCES teams (name))
okay you have very basic problem.
i don't know much about php but i can suggest you some logical thing which you can perform.
<select>
<option value="t1">Team 1</option>
<option value="t2">Team 2</option>
<option value="t3">Team 3</option>
<option value="t4">Team 4</option>
</select>
this will create drop down box. What you need to do is to set your teams id(using php) in "value" and team name between "option" tag. The "value" of the particular selected team will be passed in request when you submit your form.
ok try out this..
<?
...
mysql cnx code
...
$sql="SELECT id, name FROM Teams";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["id"];
$name=$row["name"];
$options.="<OPTION VALUE=\"$id\">".$name;
}
?>
...
html code
...
<SELECT NAME=Teams>
<OPTION VALUE=0>Choose
<?=$options?>
</SELECT>
but don't forget to wrap it with in the "form" tag.
This question is a bit broad and alot has to be cover prior to nailing the result, its almost asking how to build a website and that in itself could take years to learn. That said, these 2 links should give you what you need to get going.
W3C Forms
W3C MySql introduction and tutorials
Please note how much code is behind phpmyadmin (just go through its source code) and you will find there is no simple 1 click way off doing it.
you may try something like
<?php
$db = "database_name";
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
$query = "SELECT * FROM YOUR_TABLE";
$result = mysql_query($query);
?>
Also, in your html body part, inside your form, you may use this for generating a dropdown box
<select>
<?php
while($info = mysql_fetch_array($result)){
$name = $info["table_column_name"];
echo '<option value="'.$name.'">'.$name.'</option>';
}
?>
</select>
Hope this helps.. :)
Error: Cannot add or update a child row: a foreign key constraint fails (roflz.matches, CONSTRAINT matches_ibfk_1 FOREIGN KEY (team_home) REFERENCES teams (name))
This is all you need to know, blah blah....foreign key constraint fails blah bla....REFERENCES teams
You are updating matches, but since matches uses foreign keys to teams you cannot add something in matches that is not in teams