How to select tables from MySQL Database in php? - 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>

Related

prevent insert data to database if specific atribute already exist

I want to prevent duplicate values into a database table from a form using PHP.
I have a table data on database that have atribute dataid(auto increment as primary key), data1, data2.
And I have a simple form like this
<h2>Enter your data</h2>
<form action="script.php" method="post">
Data 1:<input type="text" name="data1" /></p>
Data 2:<textarea name="data2"></textarea></p>
<input type="submit" name="submit" value="Add Data" />
</form>
It's script.php for inserting data to database
<?php
if(isset($_POST['submit']))
{
//connect to the database
$conn = mysql_connect('host', 'username', 'password', 'dbname') or die(mysql_error());
//insert results from the form input
$query = "INSERT INTO data(data1, data2) VALUES('$_POST[data1]', '$_POST[data2]')";
$result = mysql_query($conn, $query) or die(mysql_error());
}
?>
but it will insert any data from the form to database.
How can I prevent insert data to database if data1 already exist?
The solution to your problem is to make the column unique so the database takes care of enforcing this constraint. You can do this by creating a unique index or constraint:
alter table data add constraint unq_data_data1 unique (data1);
You can then use this in an insert to ignore duplicates by using on duplicate key update:
INSERT INTO data(data1, data2)
VALUES('$_POST[data1]', '$_POST[data2]')
ON DUPLICATE KEY UPDATE data1 = VALUES(data1);
The ON DUPLICATE KEY part doesn't really do anything. It is a no-op.
Also, you should parameterize your queries, so you are not subject to SQL injection and so the query plans can be cached. But that is another matter.
make column data1 unique
ALTER TABLE `data` ADD UNIQUE (`data1`);
change your query like this to ignore insert when data exist
$query = "INSERT IGNORE INTO data(data1, data2) VALUES('$_POST[data1]', '$_POST[data2]')";

Logic for inserting form with/without optional inputs into MySQL

Using: Brackets Html editor, MySQL Workbench
Simplified, I have a database with these tables
(main table) person
idperson PK NN UN AI
*fk_job NN UN (foreign key refering to idjob)
fn NN
ln NN
job
idjob PK NN UN AI
jobname NN
adress
idadress PK NN UN AI
*fk_person NN UN (foreign key refering to idperson)
adress NN
and this form. In the form it is required to fill on one adress, and optional to fill in a second one.
<?php
$con = new mysqli("localhost","user","password","database");
if ($con->
connect_error) {
die('Error : ('. $con->connect_errno .') '. $con->connect_error .'');
}
$job_sql = "SELECT idtype, typename FROM type;";
$job_data = $con->query($job_sql);
//insert if(isset()) here
$con->close();
?>
<form method="post">
<select name="typeSlc" required>
<option disabled selected>_</option>
<?php while($row = mysqli_fetch_array($job_data)) { ?>
<option value="<?php echo $row['jobid'];?>"><?php echo $row['jobname'];?></option>
<?php } ?>
</select>
<input name="fnTxt" required type="text">
<input name="lnTxt" required type="text">
<input name="adressTxt" required type="text">
<input name="cityTxt" required type="text">
<input name="opt_adressTxt" type="text">
<input name="opt_cityTxt" type="text">
<input name="submit" value="submit" type="submit">
</form
Issue:
I want to send a transaction with one batch of queries to the server when 'opt_adress' isset and another when it is not, namely:
if(isset($_POST['submit'])) {
if(isset($_POST['opt_adress'])) {
$sql = sprintf ("BEGIN;
INSERT INTO person (fk_job, fn, ln)
VALUES (%s, '%s', '%s');
SELECT LAST_INSERT_ID() INTO #id;
INSERT INTO adress (fk_person, adress)
VALUES (#id, '%s');
INSERT INTO adress (fk_person, adress, city)
VALUES (#id, '%s', '%s');
COMMIT;",
$con->real_escape_string($_POST['jobSlc']),
$con->real_escape_string($_POST['fnTxt']),
$con->real_escape_string($_POST['lnTxt']),
$con->real_escape_string($_POST['adressTxt']),
$con->real_escape_string($_POST['cityTxt']),
$con->real_escape_string($_POST['opt_adressTxt']),
$con->real_escape_string($_POST['opt_cityTxt']))
;
} else {
$sql = sprintf ("BEGIN;
INSERT INTO person (fk_job, fn, ln)
VALUES (%s, '%s', '%s');
INSERT INTO adress (fk_person, adress, city)
VALUES (LAST_INSERT_ID(), '%s', '%s');
COMMIT;",
$con->real_escape_string($_POST['jobSlc']),
$con->real_escape_string($_POST['fnTxt']),
$con->real_escape_string($_POST['lnTxt']),
$con->real_escape_string($_POST['adressTxt']),
$con->real_escape_string($_POST['cityTxt']))
;
}
$con->query($sql);
header("Location: samepage.php");
When I try to run the query it does not go through to the database (I am using MySQL Workbench). There are no error messages, yet the query is unsuccesful.
I want to insert batches if queries in a transaction if there are existing values in the optional inputs. Is this the correct string for that? Or is there a sleeker code I can use?
The form and database in this question is a simplified version on the one I use in reality.
Thanks in advance, -burrdie
You have to understand the difference between a query and a batch of queries.
Since you have to execute several separate queries, you have to make several separate query() calls as well.
So change your code like this
$con->query("BEGIN");
$con->query(sprintf ("INSERT INTO person (fk_job, fn, ln)...");
$con->query("SELECT LAST_INSERT_ID() INTO #id");
// ...so on
and you'll be set.
Besides, it will let you write sleeker code, as you will be able to add your condition in the middle of the execution, thus not duplicating the code.

Insert no duplicate name PHP

I have this form and this function for insert name in db:
<form action="player.php#insertPlayer" method="post">
<input type="text" name="nameplayer" />
<input type="submit" value="Ajouter joueur" />
</form>
function insertPlayer($name) {
db connection
if (empty ($name))
{echo "<span style='color: red'>WRONG!!!!</span>";}
else
{
$insertplayer="INSERT INTO `player`(id, name) VALUES ('','$name');";
echo 'player insert succes';
mysql_close($db);
}
}
But if i enter 2 same name, it's work, how can i do for just have always one same name ?
To make player table column name as UNIQUE, run the below ALTER statement on your corresponding Database.
ALTER TABLE player ADD UNIQUE (name);
If already the player table has some data with duplicate values in name column, the alter statement will fail. So clear the data from player table before running the ALTER statement.

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

Error: Unknown column in 'where clause'

I have a form that is populated with mySQL db values upon loading the page. The data in the form can be edited and then a submit button that send the data to mysql to overwrite the values that were preloaded in the form. The fields are displayed in the form correctly but when changed and submitted I receive the following:
Error:Unkown column in 'where clause'.
I'm relatively new to working with mysql query's instead of taking the 'phpmyadmin' route ._.
Here's the query I used to fill the table with the original form data:
INSERT INTO mytable VALUES ("sunday", "name1", "price1"), ("monday", "name2", "$35"), ("tuesday", "name3", "$100"), ("wednesday", "name4", "$65"), ("thursday", "name5", "$5"), ("friday", "name6", "$57"), ("saturday", "name7", "$10");
Here's the sql query used to populate the form and then assigned to a variable by usingfetch_array
$sun_data = mysql_query("SELECT * FROM mytable WHERE day='sunday'")
or die(mysql_error());
... ...
$sun_info = mysql_fetch_array( $sun_data );
Then the form:
<form action="update_form.php">
<input type="text" name="sun_name" value="<?php echo $sun_info['name'] ?>" />
<input type="text" name="sun_price" value="<?php echo $sun_info['price'] ?>" />
Like I said the form updates fine but then when the form data is submitted to update_form.php I receive the error. Here is the form action update.php
$sun_day_change = $_POST['sun_name'];
$sun_price_change = $_POST['sun_price'];
$sunday = 'sunday';
$sql = "UPDATE mytable SET name = '$sun_day_change', price = '$sun_price_change' WHERE day = ".$sunday;
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
header('Location: http://localhost/form.php');
I'm assuming the issue is when I pass the values back to the database but since I have used almost the identical sql query to retrieve the values I'm not sure where I went wrong. Thanks for the help!
You are missing quotation marks in the update query, around $sunday.
$sql = "UPDATE mytable SET name = '$sun_day_change', price = '$sun_price_change' WHERE day = '".$sunday."'";

Categories