PHP post ID of dropdown statement not value - php

I have a PHP PDO statement that queries a table in my database to return a list of users.
The form is used to log maintenance events, so the username is used to log the person that has done the maintenance.
However when the form is submitted - its submitting the value of the dropdown box instead of the ID of the row it's returning. The table its submitting it into has a column "engineer" the is referencing the engineers table e.g. John Doe id = 1.
I think I need it to post the ID and not the name.. Here's my code:
<form action="" method="post">
<label>Engineer Name:</label>
<br/><br/>
<select id="teamlist" name="teamlist">
<?php
$pdo = new PDO('mysql:host=localhost;dbname=frontier_maintlog', 'user', 'pass');
#Set Error Mode to ERRMODE_EXCEPTION.
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('Select name from engineers');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option>'.$row['name'].'</option>';
}
?>
</select>
<br/><br/>
<input type="submit" value=" Submit " name="submit"/><br />
</form>
and here's the bit that does the inserting into database:
$sql = "INSERT INTO log (engineer, description, fa_description)
VALUES ('".$_POST["engineer"]."','".$_POST["description"]."','".$_POST["fa_description"]."')";
The "log" table looks a bit like this:logtableimage
Thank you! Sorry if it doesn't make perfect sense.
Here's the error I receive SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'engineer' at row 1

Error is that you are inserting string to int datatype.
You should also select id value from engineers table, to use for options:
...
$stmt = $pdo->prepare('Select id,name from engineers');
$stmt->execute();
// and assign value to options
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<option value='$row[id]'>$row[name]</option>";
}

You have to assign a value to option. Every option needs to have it's own value. In you case you just echo the option.
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
}

Related

Delete row from sql table with php issue [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
Ask the user which row to delete based on the
value selected in the select list and the value from a textbox which contains
the matching data. For example, selected item = ‘city’ and the textbox =
‘Boston’. Include a button that removes the row from the table.
those are my instructions to follow. I am having two issues, the first issue is if I say.. select teamname and enter a team from the table I get an error saying:
DELETE FROM teams WHERE teamname = rockets
Column not found: 1054 Unknown column 'rockets' in 'where clause'
its trying to use rockets as the column name and not the row that's needs to be deleted. The second issue is if I select yearformed and enter in a correct year, it will delete the row/s with that year. If i enter a year that doesn't exist, my code says records deleted successfully, but nothing is actual deleted.
I think I have got somethings mixed up here, and not sure exactly how it halfway works for yearformed and doesn't for other columns....
html
<form method='post' action='phpfiles/deleteData.php'>
Select a column name, then enter which data to delete.
<br>
<br>
<label for='option1'>
<select name='selectColumn'>
<option value='teamname' id='team'>teamname</option>
<option value='city' id='city'>city</option>
<option value='bestplayer' id='best'>bestplayer</option>
<option value='yearformed' id='year'>year</option>
<option value='website' id='website'>website</option>
</select>
</label>
<label for='option2'>
Data to delete: <input type='text' name='dataDelete'>
</label>
<br><br>
<input type='submit' value='Submit Delete'>
</form>
php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$servername = "localhost";
$username = "root";
$password = "enigma";
$dbname = "program09";
$columnSelect = $_POST['selectColumn'];
$deleteData = $_POST['dataDelete'];
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$sql = "DELETE FROM teams WHERE $columnSelect = $deleteData";
// use exec() because no results are returned
$conn->exec($sql);
echo "Record deleted successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
?>
You need single quotes:
$sql = "DELETE FROM teams WHERE $columnSelect = '$deleteData'";
But it's better to use prepared statements to avoid SQL Injection. Also use a whitelist for your column names.
$sql = "DELETE FROM teams WHERE $columnSelect = :value1";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':value1'=>$deleteData));

How can I check if a value already exists in mySQL database?

I want to store a name in the mySQL database. When I click the submit button, PHP should check if the name already exists in the database. If yes then do not submit and print an error message:
Name already exists in database.
<?php
if ( !empty($_POST)) {
$name = $_POST['name'];
$valid = true;
if ($valid) {
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO people (name) values(?) ";
$q = $pdo->prepare($sql);
$q->execute(array($name));
}
}
?>
<form action="form.php" method="post">
<input name="name" type="text" value="<?php echo !empty($name)?$name:'';?>">
<button type="submit" >Submit</button>
</form>
Try following query to check if a value already exists in mySQL database?
$q = $pdo->prepare("SELECT name FROM people WHERE name = :name LIMIT 1");
$q->bindValue(':name', '$name');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row = $check['name'];
// Do Something If name Already Exist
} else {
// Do Something If name Doesn't Exist
}
you could declare the column as unique and check if the query executes or not, for example:
$query = $pdo->prepare("SELECT name FROM table WHERE name = :name");
$query->bindValue(':name', '$name');
if ($query->execute()){
//no duplicate
}
else {
//error, check the error code.
echo "$stmt->errorCode()";
}
$query-> execute will retun true on success and false other wise, and the database will return an error when the input is a duplicate in a unique coulmn.
I think Making the duplication check in the database is safer.

MYSQL PDO insert value from drop down list functionality

In a user creation form I have one element which is a drop down list where a role_type (i.e admin) can be assigned to the user.
Im not sure how to extract the value from the drop down and set it in the 'user' table because the table in the database takes a number however the user will select the value from the drop down.
The table the drop down is populated from only has two columns 'RoleTypeCode' which is auto incremented and 'Role_Title' which is the column used to populate the drop down.
The table i wish to update is referencing the RoleTypeCode.
USER: (UserRecordID(PK - AutoIncrement), Forename, Surname, Email, RoleTypeCode(FK))
Role_Type: (RoleTypeCode(PK - AutoIncrement), Role_Title)
So far i have:
$forename = $_POST['Forename'];
$surname = $_POST['Surname'];
$email = $_POST['Email'];
$role_title = $_POST['Role_Title'];
/*** connect to database ***/
include "db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insertUser = $db_conx->prepare("INSERT INTO user (Forename, Surname, Email, Role_TypeCode ) VALUES (:forename, :surname, :email, :role_title )");
/*** bind the parameters ***/
$insertUser->bindParam(':forename', $forename, PDO::PARAM_STR);
$insertUser->bindParam(':surname', $surname, PDO::PARAM_STR);
$insertUser->bindParam(':email', $email, PDO::PARAM_STR);
$insertUser->bindParam(':role_title', $role_title, PDO::PARAM_STR);
/*** execute the prepared statement ***/
$insertUser->execute();
/*** success message ***/
$message = 'New user added';
}
catch(Exception $e)
{
/*** check if the email already exists ***/
if( $e->getCode() == 23000)
{
$message = 'This email has already been registered';
}
else
{
/*** fail message incase something went wrong ***/
$message = 'Unable to process your request. Please try again later';
}
}
not sure how to cater for role_title
any help would be much appreciated!! :)
UPDATE: the process I'm looking for is after a user hits the submit button. Trying to extract the information from the drop down and set it in the users table. The code above is for the submit file once a user has clicked 'submit'
Im not sure how to extract the value from the drop down and set it in the 'user' table because the table in the database takes a number however the user will select the value from the drop down.
The table the drop down is populated from only has two columns 'RoleTypeCode' which is auto incremented and 'Role_Title' which is the column used to populate the drop down.
You use the primary key of the RoleTypeCode as the dropdown value while you use the Role_Title as the display value. Then when you submit the form you just use the RoleTypeCode to set the FK value on the user.
So essentially you form would look like:
<?php
$stmt = $pdo->prepare('SELECT * FROM Role_Type');
$roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<form>
<label>First Name</label>
<input type="text" name="forename" />
<label>Last Name</label>
<input type="text" name="surname" />
<label>Email</label>
<input type="text" name="email" />
<label>Role</label>
<select name="role">
<?php foreach($roles as $role): ?>
<option value="<?php echo $role['RoleTypeCode'] ?>"><?php echo $role['Role_Title'] ?></option>
<?php endforeach; ?>
</select>
</form>
Then when you get your submit it would be something like:
$insertStmt = $pdo->prepare(prepare('INSERT INTO user (Forename, Surname, Email, Role_TypeCode ) VALUES (:forename, :surname, :email, :role )');
$insertStmt->execute(array(
':forname' => $_POST['forename'],
':surname' => $_POST['surname'],
':email' => $_POST['email'],
':role' => $_POST['role']
));
Use the following to populate drop down
<?php
//database connection
$sql = "SELECT * FROM Role_Type";
$db_conx->query($sql); //query as no parameters
//create html for drop down
$SelectHtml = "<select name='Role_Title' id='Role_Title'>\n";//Name and id to suit
while($row = $db_conx->fetch()) {
$SelectHtml .=<optionvalue='".$row[$RoleTypeCode]."'>".$row[$Role_Title]."</option>\n";
}
$SelectHtml .= "<select>\n";
?>
HTML to show drop down
<form action="xxx">
form stuff
<?php echo $SelectHtml ?>
more form stuff
Use to update using RoleTypeCode value which is FK to UserRecordID in USER
If I understand your question correctly, what you want can be accomplished using AJAX -- which sounds complicated, but isn't. However, it is handled on the front end.
Here are some good posts for getting the basics of AJAX:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1

Connecting html form to php page according to primary key

Ok so essentially what I'm trying to do is add a q&a component to my website (first website, so my current php knowledge is minimal). I have the html page where the user's input is recorded, and added to the database, but then I'm having trouble pulling that specific info from the database.
My current php page is pulling info where the questiondetail = the question detail (detail='$detail') in the database, but that could potentially present a problem if two users enter the same information as their question details (unlikely, but still possible, especially if the same person accidentally submits the question twice). What I want to do is have the page load according to the database's question_id (primary key) which is the only thing that will always be unique.
HTML CODE:
<form id="question_outline" action="process.php" method="get">
<p><textarea name="title" id="title_layout" type="text" placeholder="Question Title" ></textarea> </p>
<textarea name="detail" id= "detail_layout" type="text" placeholder="Question Details" ></textarea>
<div id="break"> </div>
<input id="submit_form" name="submit_question" value="Submit Question" type="submit" />
</form>
PROCESS.PHP CODE:
$name2 = $_GET['name2'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$query= "INSERT INTO questions (title, detail) VALUES ('$title', '$detail')";
$result = mysql_query("SELECT * FROM questions where detail='$detail' ")
or die(mysql_error());
The info is being stored correctly in the database, and is being pulled out successfully when detail=$detail, but what I'm looking to do is have it pulled out according to the question_id because that is the only value that will always be unique. Any response will be greatly appreciated!
Updated Version
QUESTION_EXAMPLE.PHP CODE
<?php
$server_name = "my_servername";
$db_user_name ="my_username";
$db_password = "my_password";
$database = "my_database";
$submit = $_GET['submit'];
$title = $_GET['title'];
$detail = $_GET['detail'];
$conn = mysql_connect($server_name, $db_user_name, $db_password);
mysql_select_db($database) or die( "Unable to select database");
$result = mysql_query("SELECT title, detail FROM questions WHERE id =" .
mysql_real_escape_string($_GET["id"]), $conn);
$row = mysql_fetch_assoc($result);
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Firstly, if that is code to be used in production, please make sure you are escaping your SQL parameters before plugging them in to your statement. Nobody enjoys a SQL injection attack. I would recommend using PDO instead as it supports prepared statements and parameter binding which is much much safer.
How can I prevent SQL injection in PHP?
So you have a form...
[title]
[details]
[submit]
And that gets inserted into your database...
INSERT INTO questions (title, details) VALUES (?, ?)
You can get the last insert id using mysql_insert_id, http://php.net/manual/en/function.mysql-insert-id.php.
$id = mysql_insert_id();
Then you can get the record...
SELECT title, details FROM questions WHERE id = ?
And output it in a preview page.
I have written an example using PDO instead of the basic mysql functions.
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$pdo = new PDO("mysql:dbname=test");
// Prepare the insert statement and bind parameters
$stmt = $pdo->prepare("INSERT INTO questions (title, detail) VALUES (?, ?)");
$stmt->bindValue(1, $_POST["title"], PDO::PARAM_STR);
$stmt->bindValue(2, $_POST["detail"], PDO::PARAM_STR);
// Execute the insert statement
$stmt->execute();
// Retrieve the id
$id = $stmt->lastInsertId();
// Prepare a select statement and bind the id parameter
$stmt = $pdo->prepare("SELECT title, detail FROM questions WHERE id = ?");
$stmt->bindValue(1, $id, PDO::PARAM_INT);
// Execute the select statement
$stmt->execute();
// Retrieve the record as an associative array
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
Without PDO...
form.php:
<form action="process.php" method="post">
<label for="question_title">Title</label>
<input id="question_title" name="title"/>
<label for="question_detail">Detail</label>
<input id="question_detail" name="detail"/>
<button type="submit">Submit</button>
</form>
process.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute the insert statement safely
mysql_query("INSERT INTO questions (title, detail) VALUES ('" .
mysql_real_escape_string($_POST["title"]) . "','" .
mysql_real_escape_string($_POST["detail"]) . "')", $conn);
// Retrieve the id
$id = mysql_insert_id($conn);
// Close the connection
mysql_close($conn);
header("Location: question_preview.php?id=$id");
question_preview.php:
<?php
// Create a database connection
$conn = mysql_connect();
// Execute a select statement safely
$result = mysql_query("SELECT title, detail FROM questions WHERE id = " .
mysql_real_escape_string($_GET["id"]), $conn);
// Retrieve the record as an associative array
$row = mysql_fetch_assoc($result);
// Close the connection
mysql_close($conn);
?>
<h1><?php echo htmlspecialchars($row["title"]);?></h1>
<p><?php echo htmlspecialchars($row["detail"]);?></p>
I assume you want to sort the questions according to the question_id. You could try using the ORDER BY command
example -
$result = mysql_query("SELECT * FROM questions where detail='$detail' ORDER BY question_id")
For these type of examples, you need to run Transaction within database
below are the
http://dev.mysql.com/doc/refman/5.0/en/commit.html
Or else
Create an random variable stored in session and also insert into database and you call it from database and you can preview it easily.
id | question_code | q_title
question_code is the random value generated before insertion into database,
and save the question_code in a session and again call it for preview.

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