I have a select dropdown list that contains all existing usernames found in my table. I want to delete an entry from my table by selecting the corresponding username. I can't seem to find the error in my php file...I get the "Successfully deleted" message even if the entry is still there. Want to know what's wrong with my php. Thanks.
Here's the concerned portion of the View:
<form action="deleting.php" method="post">
<select id="username">
<option ng-repeat="user in users">
{{user.username}}
</option>
</select>
<input type="submit" value="Delete"/>
</form>
Here's my deleting.php file
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "abc";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$deletecontent= isset( $_POST["username"] ) ? $_POST["username"] : "null" ;
$sql = "DELETE from users where username='$deletecontent'";
if (mysqli_query($conn, $sql)) {
echo "Successfully deleted";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
You can get value in $_POST only when there is name attribute in your input. so try
<select id="username" name="username">
You have to add name attribute to select option. Then only it can be accessed using $_POST.
<select id="username" name = "username">
Set name="username" in <select>
and,
set value attribute in <option>.
<form action="deleting.php" method="post">
<select id="username" name="username">
<option ng-repeat="user in users" value="{{user.username}}">
{{user.username}}
</option>
</select>
<input type="submit" value="Delete"/>
</form>
Related
This question already has answers here:
PHP update table in MySQL not working
(2 answers)
Closed 6 years ago.
I have received an ID from a get request and put it into new variable $id. I am trying to include this variable in an SQL query but it doesn't work. It does however work when I hardcode the ID.
This works fine.
$query = "UPDATE products SET p_name = " . "'TEST' WHERE p_id=000007;";
The following code does NOT work. Can anyone explain it?
$query = "UPDATE products SET p_name = " . "'TEST' WHERE p_id=" . $id . ";";
All of my code if anyone can help:
<?php
// Connection file
//require 'db.php';
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check Connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$id = $_GET['id'];
echo $id;
if (isset($_POST["updateSubmit"])) {
$query = "UPDATE products SET p_name = " . "'TEST' WHERE p_id=" . $id . ";";
$result = mysqli_query($conn, $query);
}
?>
<div>
<form id="updateForm" name="updateForm" action="update.php" method="post">
<label>Product name:</label><br>
<input type="text" name="updateProductName"><br>
<label>Product type</label><br>
<select name="updateProductType">
<option value="Jackets/coats">Jackets/coats</option>
<option value="Accessories">Accessories</option>
<option value="Shirts">Shirts</option>
<option value="Jeans">Jeans</option>
<option value="Trousers">Trousers</option>
<option value="Shoes">Shoes</option>
<option value="Suits">Suits</option>
</select>
<p>Product description:</p>
<textarea name="updateProductDesc" rows="10" cols="30"></textarea><br>
<label>Product price:</label><br>
<input type="text" name="updateProductPrice"><br>
<label>Stock level:</label><br>
<input type="text" name="updateProductStock"><br>
<input type="submit" name="updateSubmit" value="Submit">
</form>
</div>
<?php
?>
I have used this link from another page which contains the ID.
<a href="update.php?mode=update&id=<?php echo $productDetails['p_id']; ?>"
title="Update <?php echo $productDetails['p_name']; ?>">Update</a>
You didn't get id because there is no id in your url
<form id="updateForm" name="updateForm" action="update.php?id=<?php echo $id; ?>" method="post">
or pass id as hidden like
<input type="hidden" name="id" id="your_id"/>
Change your query to
$query = "UPDATE products SET p_name = 'TEST' WHERE p_id=". $id;
Technically it accepts all the input but there no any error message that there is something wrong with my code. The insert is located at the bottom part of the code which is strangely not working because I tried my insert statement in the database and of course changing the variables with real values and it worked that way.
Tried this insert statement in my workbench and it worked:
INSERT INTO members (organization,login,password,name,title,profil,created,logout_time,timezone) VALUES ('1','Kristen','123','Kristen Crooks','Volunteer','2','2016-10-11 14:09','0','0')
Code:
<html>
<head>
<meta charset="UTF-8">
<title></title>
<center><b> Volunteer Management </b></center>
<center>
Add User
Add Skills
Assign User
</center>
</head>
<body>
<?php
$config = parse_ini_file('/config.ini');
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT skillName FROM skills";
$result = $conn->query($sql);
$num=mysqli_num_rows($result);
$conn->close();
?>
<form method="get">
Username: <br>
<input type="text" name="username"> <br>
Password: <br>
<input type="text" name="password"> <br>
Name: <br>
<input type="text" name="name"> <br>
Title: <br>
<input type="text" name="title"> <br> <br>
Permission:
<select id="permission" name="permission">
<option selected disabled>Choose here</option>
<option value="0">Admin</option>
<option value="1">Project Manager</option>
<option value="2">Volunteer</option>
<option value="6">Accounting Officer</option>
</select> <br><br>
Skills: <br>
<?php
$i=0;while ($row = mysqli_fetch_assoc($result)) {
$skillName=$row['skillName'];
?>
<input type="checkbox" name="skills" value="<?php echo $skillName; ?>" ><?php echo $skillName; ?><br>
<?php $i++;} ?>
<br>
<input type="submit" name="submit">
</form>
<?php
if(isset($_GET['submit']))
{
$config = parse_ini_file('/config.ini');
$conn = new mysqli($config['servername'], $config['username'], $config['password'], $config['database']);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$login = $_GET['username'];
$password = $_GET['password'];
$name = $_GET['name'];
$title = $_GET['title'];
$profil = $_GET['permission'];
$created = date('Y-m-d H:i:s');
$sql = "INSERT INTO members (organization,login,password,name,title,profil,created,logout_time,timezone)
VALUES ('1','$login','$password','$name','$title','$profil','$created','0','0')";
$result = $conn->query($sql) or die('Error, insert query failed');
$conn->close();
}
?>
</body>
Okay I already dissected the code and it appears that the $created = date('Y-m-d H:i:s'); is causing the error. By the time I tried not to include it in the data in the insert statement, it worked! I guess I have to get another way to get the date from the system.
Also I've checked that the reason why there is an error is because the date format is in VARCHAR and not in date and another problem is that it does not fit in the length that set. Although I want to ask why it is not detected by the server that there is an error like that
Check PHP log and mysql log, write what is there.
Put an echo before the INSERT, check if your script comes to that place.
If echo is not working- then the problem is not in INSERT
I'm an high school Italian student, and today my professor assigned me a simple homework:
I have to create a PHP page with a basic form that allows me to introduce a new "student" into a table in MySQL, "name", "surname" and "class".
That's the PHP page:
<html>
<head>
<title> School </title>
</head>
<body>
<?php
$name="";
$surname="";
$conn=mysqli_connect("127.0.0.1","root","");
if(!$conn){ echo 'No connection.'; die;}
if(!mysqli_select_db($conn,"School")) { echo 'Err'; die;}
$result=mysqli_query($conn,"select * from classes");
if(!isset($_REQUEST["submit"])){
echo '<form action="" method="post">
<input type="text" name="name" size="26"> Name <br><br>
<input type="text" name="surname" size="26"> Surname <br><br>
<input type="submit" name="submit" value="Submit">';
if(mysqli_num_rows($result)!=0){
echo '<select name="combobox" id="combobox">
<option value="" selected="selected"> Classes list </option>';
while($combobox=mysqli_fetch_assoc($result)){
$classes=$combobox["classes"];
echo '<option value="'.$combobox["classes"].'">'.$combobox["classes"].'</option>';
}
echo '</select><br><br>';
}
echo '</form>';
}
else{
$name=$_REQUEST["name"];
$surname=$_REQUEST["surname"];
//$query='insert into Students(name,surname,classes) values("'.$name.'","'.$surname.'","'.$classes.'");';
//if(!mysqli_query($conn,$query)) { echo 'Err'; die; }
echo 'Success! <br> Name: '.$name.' <br> Surname: '.$surname.'<br> Class: '.$classes.'<br>';
}
?>
</body>
</html>
I have already created the database with all the tables I need. Now, the thing is, how do I put the "option" that I choose from the <select> into a variable so I can use it for the insert into? Everything I found was just "filling a combobox from mysql".
To get value of select give it name and after get it by it's name with $_GET['name'] or $_POST['name'] if you choose method="post", you will get the selected option value.
html:
<form method="get" action="/script.php">
<select name="name"><option>1</option></select>
<input type="submit" value="send">
</form>
php:
$value=$_GET['name'];
echo $value;
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyDB (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This is what you should follow.
Always give your form elements a name, this is how it gets sent to the backend. With <select>, the value of the selected element will be sent to your code via the name you gave it. Once you do this, you can add a variable for it at the end of your code.
Why this code is not update information?
HTML Form:
<form>
<lable> ID# :</lable>
<input id= "ID" name= "ID" type= "text">
<p>
<label>Select field to Edit</label>
<select name="change">
<option value=""></option>
<option value="fname">First Name</option>
<option value="lname">Last Name</option>
<option value="email">Email</option>
<option value="city">City</option>
<option value="zip">Zip</option>
</select>
<lable> Enter the value to be replaced </label>
<input id = "replace" name = "replace" type = "text">
</p>
<input name="submit" type="submit" value="Submit">
PHP Code for updating information from database:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$conn = mysql_connect($servername,$username,$password);
if(!$conn)
{
die('Error!' . mysqli_error());
}
$sql = 'SELECT * FROM users';
mysql_select_db('mitsdatabase');
$retval = mysql_query($sql, $conn);
if(! $retval)
{
die('Could not get data:' . mysql_error());
}
echo "<table width='300' cellpadding='5' border='1'>";
echo "<tr> <td>ID#</td> <td>FirstName</td> <td>LastName</td> <td> Email </td> <td> City </td> <td> State </td> <td> Zip </td> </tr>";
while($row = mysql_fetch_array($retval,MYSQL_ASSOC))
{
echo "<tr> <td>{$row['ID']}</td> . <td>{$row['fname']}</td> . <td>{$row['lname']}</td> . <td>{$row['email']}</td> . <td>{$row['city']}</td> . <td>{$row['state']} </td>. <td>{$row['zip']}</td>";
}
echo "</table>";
$db_id = $_POST['ID'];
$db_select = $_POST['change'];
$db_replace= $_POST['replace'];
echo " Do you want to edit any entry?";
if(!_POST['submit'])
{
echo " ";
}
else{
mysqli_query("UPDATE users SET db_select='$db_replace' WHERE ID = $db_id ");
}
mysql_close($conn);
?>
I want to update informate selected from select field but somehow it is not doing any thing. Can someone help me what is wrong with this code.
Is your PHP on the same page as your HTML? If not, you are not directing to your php code within the <form> element in your HTML.
For example, if your PHP file was called 'myphpcode.php' (and in the same folder as your HTML code) then you could direct to it using the following:
<form method="post" action="myphpcode.php">
If you want to post to the same page just change <form> to <form method="post" action="#"> and get variables in php like this $nameofvar = $_POST['nameofinputfield'] . Each input field should have the name tag.
Also try to change your mysql connect to this :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
and after you finished the query
$conn->close();
and the query to insert
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
and you can modify this $sql string to update or delete
Using AJAX How can I generate selections for a dropdown menu based on records available in a database?.
How can then use these selections to prefill a form with record/row data from a database when selected?
Heres a mock up I created of what I'm trying to do:
http://oi58.tinypic.com/2urb2ae.jpg
PHP FILE: contact_form.php
-----------------------------------------------------------
<?php
define('DB_NAME', 'xxx');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'xxx');
define('DB_HOST', 'xxx');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$connection){
die('Database connection failed: ' . mysqli_connect_error());
}
$db_selected = mysqli_select_db($connection, DB_NAME);
if(!$db_selected){
die('Can\'t use ' .DB_NAME . ' : ' . mysqli_connect_error());
}
echo 'Connected successfully';
if (isset($_POST['itemname'])){
$itm = $_POST['itemname'];
}
else {
$itm = '';
}
if($_POST['mile']){
$mi = $_POST['mile'];
}else{
echo "Miles not received";
exit;
}
if($_POST['email']){
$email = $_POST['email'];
}else{
echo "email not received";
exit;
}
$sql = "INSERT INTO seguin_orders (itemname, mile, email)
VALUES ('$itm', '$mi', '$email')";
if (!mysqli_query($connection, $sql)){
die('Error: ' . mysqli_connect_error($connection));
}
CONACT FORM: formz.php
------------------------------------------------------------------------------
<html>
<header>
</header>
<body>
<form action="/demoform/contact_form.php" class="well" id="contactForm" method="post" name="sendMsg" novalidate="">
<big>LOAD PAST ORDERS:</big>
<select id="extrafield1" name="extrafield1">
<option value="">Please select...</option>
<?php
$email = $_POST['email'];
$query="select * from tablename WHERE email={$_POST['email']}";
$res=mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($res))
{
?>
<option value="<?php echo $row['fieldname']; ?>"><?php echo $row['fieldname']; ?></option>
<?php
}
?>
</select>
</br>
<input type="text" required id="mile" name="mile" placeholder="Miles"/>
</br>
<input id="email" name="email" placeholder="Email" required="" type="text" value="demo#gmail.com" readonly="readonly"/>
</br>
<input id="name" name="itemname" placeholder="ITEM NAME 1" required="" type="text" />
</br>
<input type="reset" value="Reset" />
<button type="submit" value="Submit">Submit</button>
</form>
</body>
</html>
Using an exemple, let's assume you want to fill the "name" select based on the option selected at the "gender" select:
<select name="gender" id="gender">
<option value="m">Male</select>
<option value="f">Female</select>
</select>
When nothing is selected yet, the "name" select is empty:
<select name="name" id="name">
<option value="NULL">Please select a gender first</option>
</select>
So, what you gotta do is: when the gender select got some selection, you populate the name select with values based on the gender select option.
$(document).ready(function() {
$('select#gender').change(function(){
$('select#name').load('LOAD_NAMES_BASED_ON_GENDER.php?gender='+$(this).val());
});
});
And your PHP file responsible for loading the names based on gender should look like:
$gender = $_GET['gender'];
$list = // the way you retrieve your list of names from your DB
And then you loop this $list into an list of options, such like:
foreach($list as $key=>$value)
echo '<option value="$key">$value</option>';
This simple.
PS: the load() function is kind of an alias for the $.ajax request, given that the only purpose here is to retrieve data.