Unable to select a result from drop down list - php

I am new to this and i am trying to write a script where it will query the DB and return all the usernames in a drop down list and then to copy out the selected name and then when you register a Dog to them it will copy the name into the DB,
So Owners can have many dogs but dog can only have 1 owner...
i can enter Name and Breed but not the results from the drop down list,
i did try to get java script to pull the selected item in drop down to be where the $ownername is in in the 'insert into...' script
can you send me a message if you can help me with this i will link you the files to download
mysql_query("INSERT INTO `dog`(`id`, `dogname`, `breed`, `owner`)
VALUES ('', '$reg_dogname', '$breed', '$row');") or die (mysql_error());
$userid = mysql_insert_id();
}}
$sql = mysql_query('SELECT `username` FROM `users`');
$ownername = array();
while ($row = mysql_fetch_array($sql)){
$ownername[] = $row;
<select id="dropdown" name="dropdown" onchange="selectDropdown()">
<?php
foreach ($ownername as $ownername1) {
?>
<option value="<?php echo $ownername1['username']?>">
<?php echo $ownername1['username']?>
</option>
<?php
}
?>
</select>

It will be difficult to give you a problem specific answer until you post your code, but I think this would work pretty well for you:
-create relational tables for owners, breeds, and dogs:
Table: owners
Fields:
id_key: integer, auto number, primary key - table index
owner: varchar, 16 character, unique index - account records (unique prevents duplicate account records)
password: varchar, 32 character (assuming you are using md5 encryption, you will always get a 32 character result. Additional security concerns are beyond the scope of this question)
any other account related fields (but not dogs, give them their own table)
Table: breeds
Fields:
id_key: integer, auto number, primary key - table index
breed: varchar, 16 character, unique - available dog breeds
Table: dogs
Fields:
id_key: integer, auto number, primary key - table index
dog: varchar, 16 character, index - dog owned by account
breed: varchar, 32 character, index, foreign key= breeds.breed on delete=restrict on update=cascade (prevents duplicate breed entries during data entry)
owner: varchar, 16 character, index, foreign key= owners.owner on delete=cascade on update=cascade (this constricts the dog owner to existing accounts)
Then make a form something like this:
<?php
$formdata=array(
owners => array(),
breeds => array()
);
require_once 'dbconnection.php';
echo '<form id="dog_input" name="dog_input" method="post">';
$result=mysql_query("SELECT `owner` FROM owners;");
while ($row = mysql_fetch_row($result)) {
array_push($formdata[owners], $row[0]);
}
$result=mysql_query("SELECT `breed` FROM breeds;");
while ($row = mysql_fetch_row($result)) {
array_push($formdata[breeds], $row[0]);
}
?>
<FORM name="dog_input" method="post" action="dog_data.php">
<ul>
<li>
<label for="owner">Dog Owner</label>
<SELECT name="owner" id="owner">
<?php
foreach ($formdata[owners] as $i) {
echo '<OPTION>'.$i.'</OPTION>';
>
?>
</SELECT>
</li>
<li>
<label for="breed">Dog Breed</label>
<SELECT name="breed" id="breed">
<?php
foreach ($formdata[breeds] as $i) {
echo '<OPTION>'.$i.'</OPTION>';
>
?>
</SELECT>
</li>
<li>
<label for="dog">Dog Name</label>
<INPUT type="text" name="dog" />
</li>
<li><INPUT type="submit" value="Submit /></li>
</ul>
</FORM>
Then you need to create the validation script that will check your results and enter safe data into the database:
<?php
/*
* dog_data.php - checks data and inserts it into the database.
*/
require_once 'dbconnection.php';
$owner = $_POST['owner'];
$breed = $_POST['breed'];
$dog = mysql_real_escape_string($_POST['owner']);
//perform any additional data validation here, use an if statement to check validation before insert query if you do so
mysql_query("INSERT INTO `dogs` (`id_key`, `owner`, `breed`, `dog`)
VALUES(DEFAULT, '".$owner."', '".$breed."', '".$dog."');");
mysql_close($con);
header(" Location: http://www.example-redirection-page.com");
?>

Related

Linking foreign keys between tables

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'

Problem with query to update foreign key column

I am working on a cms for properties/ads in oop php for learning purposes. I have three tables that are connected with pivot table.
photos (id, name, extension),
property_photo (id, property_id, photo_id),
properties (id, title, description, main_photo_id)
I have a gallery of photos for every property and I am trying to be able to insert main photo (one of existing photos in gallery) for each property through foreign key (main_photo_id) and display that photo on a different page. I am having trouble writing function (query) in model. Any help is much appreciated. Here is some of my code:
AdModel:
public function MainPhotoInsert($id)
{
$this->db->query('INSERT INTO properties (main_photo_id) VALUES (:main_photo_id) SELECT id FROM PHOTOS WHERE id = :id LIMIT 1');
$this->db->bind(':id', $id);
$row = $this->db->single();
return $row;
}
AdsController:
public function galleryAction()
{
if (!isset($_GET['id'])) {
$photo_id = $_SESSION['photo_id'];
} else {
$photo_id = $_GET['id'];
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if(isset($_POST['radio']))
{
$this->AdModel->MainPhotoInsert($photo_id);
redirect('ads/index');
}
}
$data = $this->AdModel->getPhotosForProperty($photo_id);
$data1 = $this->AdModel->MainPhotoData($photo_id);
$this->view->render('ads/gallery', $data, $data1);
}
gallery.php:
<form action="/ads/gallery?id=<?php echo $_GET['id']; ?>" method="POST">
<?php foreach ($data as $key => $value) : ?>
<img src="<?php echo '/public/photos/'.$value->name.'.'.$value->extension ?>" class="img-fluid img-thumbnail" width="250" height="250">
<input type="radio" name="radio" value="<?php echo $value->photo_id; ?>" >Make main
<br>
<?php endforeach; ?>
<br>
<br>
<button type="submit" name="submit" value="submit" class="btn btn-success form-control">Submit</button>
</form>
You shouldn't have a select clause in your insert statement (at least not for what you are trying to do). IF you only ever need to set it once then you need to tweak the query to include the other two values (title and description) or they will always be blank. It should end up looking something like this:
INSERT INTO properties (main_photo_id, title, description) VALUES (:main_photo_id, : title, : description)
More likely, you want an upsert (update if a relevant row already exists, insert if one doesn't). In MySQL the syntax is insert ... on duplicate key update. This means you are going to need a primary key on the properties table (it's unclear if you already have one). The syntax is pretty similar to the insert above but without knowing the exact structure of the table I can't give you the exact query.
Update:
The on duplicate key syntax would look something like this (it depends on how you have your primary key set up on the table, e.g. if main_photo_id is the primary key then this likely won't work):
INSERT INTO properties
(id, main_photo_id, title, description)
VALUES
(:id, :main_photo_id, : title, : description)
ON DUPLICATE KEY UPDATE
main_photo_id = :main_photo_id,
title = :title,
description = :description
Side note:
gallery.php is also going to produce a separate HTML form for each image with one radio button on the form which isn't really what you want. You should move the form to wrap around the entire foreach loop so that you have one form. Then you should put the image ID as the value for the radio button.

how to Insert Primary key instead of name column in database

I am developing a hotel reservation system in PHP using MySQL.
I want to know how to insert primary key value instead of name in the database. user select hotel name from drop down , instead of putting hotel name in database I want to insert hotel_id.
where I have a page named with ADD New room where the user will add new rooms.
table related to add new room page is: room in MySQL
in that page, I have a form where the user has to select hotel name from a select tag which is populated dynamically from a database table named as hotels.
I want to insert hotel_id which is a foreign key in room table correspondence to the selected hotel name
Below is the code which shows select tag populated with the hotel name.
<div class="form-group">
<label class="form-label">Hotel Name</label>
<select class="form-control" name="name" id="name">
<?php
$sel_cus = "select * from hotels ";
$res_cus = mysqli_query($connection, $sel_cus);
while ($row = mysqli_fetch_array($res_cus)) {
?>
<option value="<?php echo $row['hotel_name']; ?>"><?php echo $row['hotel_name']; ?></option>
<?php
}
?>
</select>
</div>
when i insert room record in database using below code it insert hotel name instead of hotel_id. I want to insert hotel_id in room table.
Please guide me with code example. Thanks
if (isset($_POST['submit'])) {
$hotel_name = $_POST['name'];
$date = date('m-dd-yy');
$query = "INSERT INTO room (Hotel_Id, date)
VALUES ('$hotel_name ','$date')";
}
You need to use the option value. Currently you are using hotel_name as option value, change this to hotel_id and you should be fine.
<option value="<?php echo $row['hotel_id']; ?>"><?php echo $row['hotel_name'];?></option>

How to select tables from MySQL Database in php?

I am trying to create a form in PHP with MySQL involved.
The theme of this form, form.php, is all about drinks. There are thirteen tables -each table named after type of drink (Belgian beer, wine, soda, rum, ...) that all include only three columns: Id of the drink(PRIVATE KEY AUTO_INCREMENT), the name of the drink and the price (in char). The rest of the columns in other tables are the same, the values are different.
I want to create a dropdown that allows you to select tables from MySQL to add/delete data to the columns within the selected table.
Some names of tables, columns and form elements are named in Dutch.
Click here to see resources
These are the things I do know:
1)Php code to add data to database
<?php
if ( ! empty($_POST))
{
$mysqli = new mysqli('localhost','root','','welkom');
if ($mysqli ->connect_error)
{
die('connect error: '. $mysqli->connect_errno . ': ' . $mysqli->connect_error);
}
$sql = "INSERT INTO abdijbieren (naam, prijs) VALUES ('{$mysqli->real_escape_string($_POST['naam'])}','{$mysqli->real_escape_string($_POST['prijs'])}')";
$insert = $mysqli->query($sql);
if ($insert)
{
echo "Success! Row ID: {$mysqli->insert_id}";
}
else
{
die("Error: {$mysqli->errno} : {$mysqli->error}");
}
$mysqli->close();
}?>
2)Form
<form method="post" action="check.php"> <!--check.php is not made yet but when that happens it should be used to automatically update the selected table and auto-return to form.php -->
<input name="naam" type="text" placeholder="naam drank/snack" required><br>
<input name="prijs" type="text" placeholder="prijs" required><br>
<input type="submit" value="Submit form">
</form>
All I can do with it is to add data to one certain column.
If you know how I can solve this, you are my hero.
You can select table names like this:
SHOW TABLES FROM <your_database>
Also to select columns from a table:
SHOW COLUMNS FROM <your_table>

How can I make a web form with drop down boxes to insert data into a relational database

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

Categories