Reputation: 53
Probably a beginners mistake but my PHP $_POST seems to delete part of the value which is submitted via the form.
The code below works perfectly fine if $company_name is just one word (without spaces) but for values with spaces it does not seem to work...
I use the following code to submit the form:
<form action='deletecompany.php' method='post'>
Company name:
<select name="company_name">
<?php
$sql = "SELECT company_name FROM company";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value=".$row["company_name"].">" . $row["company_name"]. "</option>";
}
} else {
echo "The database does not include any countries.";
}
?>
</select>
<input type='submit'>
</form>
In the dropdown menu the values are correctly shows as (for example) 'Company in Country Y'.
However, when I then use the posted value in the deletecompany.php file only the first word ('Company') would come through.
I use the following code in deletecompany.php:
if (isset($_POST["company_name"])){
// delete from database
$company_name = $_POST["company_name"];
$delete_company = "DELETE FROM company WHERE company_name='$company_name'";
if ($conn->query($delete_company) === TRUE) {
echo $company_name . " has been deleted successfully!";
} else {
echo "Error: " . $delete_company . "<br>" . $conn->error;
}
}
The output of the deletecompany.php page would be 'Company has been deleted succesfully!' but in fact no Company is actually deleted since there is no such value in the relevant MYSQL colomn (there is a value 'Company in Country Y').
Does $_POST automatically delete part of the value or do I miss something else here?
Thanks!
Upvotes: 2
Views: 2306
Reputation: 785
Your option values have not been correctly enclosed, hence why the browser is only taking the first word of the string.
echo "<option value=".$row["company_name"].">" . $row["company_name"]. "</option>";
You need to enclose the option value, like this:
echo "<option value='".$row["company_name"]."'>" . $row["company_name"]. "</option>";
Upvotes: 3