Getting value from dropdown and use it in query - php

i am having trouble in deleteing values from my database using php can someone help me plsss this is for my project
this is where i get the value
<select name="fname" id='mySelect' value='Foodname'>
and this is what i want to do after i submit it
if(isset($_POST['submit']))
{
$food = $_POST['fname'];
echo $food;
if($food=='')
{
echo"<script>alert('Please Dont Leave any Blanks')</script>";
}
else
{
sqldel="DELETE FROM menu WHERE food = $food;";
}
}

This is how your complete code should be look like. Hope it helps!!!
<form name="" method="post" action="">
<select name="fname" id='mySelect' value='Foodname'>
<option value="">select</option>
<option value="option1">option1</option>
<option value="print server, printer">print server, printer</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
<?php
//Check if Form is submitted
if(isset($_POST['submit']))
{
//Store submitted value in variable
$food = $_POST['fname'];
echo $food;
//Check if the submitted value is blank or not
if($food=='')
{
//User submitted blank value - so throw an error
echo"<script>alert('Please Dont Leave any Blanks')</script>";
}
else
{
/*user selected a valid value in drop down so we are in else part*/
//This is your database configuration settings
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "yourDBName";
// Create connection - here you are doing database connection
$conn = new mysqli($servername, $username, $password, $dbname);
/* Check connection - If you database configuration settings are wrong it will throw an error and stop there itself and wont execute your further code*/
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
/*Now Check if record exists in db for the selected value. If record exists in database than only we can delete record.*/
$sql = "SELECT id FROM menu WHERE food = '".$food."'";
$result = $conn->query($sql);
/*check if select query return a row greater than 0, implies record exists in table */
if ($result->num_rows > 0) {
/*Record exists in database so - sql to delete a record*/
$delete_sql = "DELETE FROM menu WHERE food = '".$food."' ";
/*this will execute the delete query, if it return true we will show success alert else throw an error*/
if ($conn->query($delete_sql) === TRUE) {
echo"<script>alert('Record deleted successfully')</script>";
} else {
echo "Error deleting record: " . $conn->error;
}
} else {
echo"<script>alert('No record found for the seleted item')</script>";
}
//Close database connection
$conn->close();
}
}
?>

just remove ; after query and put single quote around variable $food
sqldel="DELETE FROM menu WHERE food = $food;";
shoulb be
sqldel="DELETE FROM menu WHERE food = '$food'";

Here is a fix for your query:
$sqldel = "DELETE FROM menu WHERE food = '".$food."'";

You need to put quotes around $food.
$sqldel="DELETE FROM menu WHERE food = '$food';";

Related

Trying to compare a value from the database from the url after the?

I'm trying to get a value from the database and compare it with whatever id href was set. But nothing happens.
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "products";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$id = $row["id"];
echo <<<EOT
<br>
<form action='index.php?$id' method="POST">
<input type='submit' name="submit" value="more">
</form>
EOT;
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
while($row = $result->fetch_assoc()) {
if ($_SERVER["QUERY_STRING"] == $row) {
echo 'you clicked something from the database' . $id;
}
}
}
$conn->close();
?>
Trying to eventually get a value from the database then individually show a description if the more href is clicked.
your answer has a high time complexity you can easily make you
SQL query
SELECT id FROM items WHERE id = ?
and if the rows number is 0 this is mean there is no record with this id
you can check row's number from num_rows
You will never see "you clicked something from the database" message because you already fetched the result from your query in the first loop, check this question why-cant-i-loop-twice-on-mysqli-fetch-array-results
An option is to save the result in an array to use it later in your second loop
//your first loop
$savedRows = [];
while($row = $result->fetch_assoc()) {
$savedRows[] = $row;
//the rest of your code
}
// ......
// your second loop
if (isset($_POST['submit'])) {
foreach($savedRows as $row) {
if ($_SERVER["QUERY_STRING"] == $row['id']) {
echo 'you clicked something from the database ' . $id;
}
}
}
Also note that if this is your actual code, you need to make the closing identifier of your herodoc EOT; the first character on it's line, otherwise the rest of the file will be part of this string

mysql updating data only where post contains data

i have a simple form in html where user selects and ID from the table on the website (required data) and then he can / or not change 2 fields. First is a dropdown list of 2 values (strings), and the second is number of open spots!
So if a user leaves both fields empty and click send by mistake nothing should happen. If a user only changes one of the fields only that one should change!
I have checked every forum and almost all posts in here and i still cannot get it to work.
<form action="viv_settings_tecaji.php" method="post">
Datum termina (izberi ID):
<input type="number" name="ID" required><br><br>
<!--Sprememba tega datuma (če ne želiš spremenit pusti prazno):
<input type="date" name="nov_datum"><br><br>-->
Sprememba statusa (če želiš da ostane isto vpiši trenutni status!:
<select name="STATUS">
<option></option>
<option value="zaprt">Zaprt</option>
<option value="odprt">Odprt</option>
</select><br><br>
Sprememba števila odprtih mest
<input type="number" name="st_odprtih_mest"><br><br>
<input type="submit">
</form><br>
php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "viverius_education";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$update_status = $_POST['STATUS'];
$update_st_odprtih_mest = $_POST['st_odprtih_mest'];
$update_ID = $_POST['ID'];
if (empty($update_status) AND empty($update_status)){
header('Location: viv_settings_tecaji_main.php'); exit;
}
else{
$sql = "UPDATE razpisani_tecaji
SET
STATUS = IF('$update_status'='',STATUS,'$update_status'),
ST_ODPRTIH_MEST = IF('$update_st_odprtih_mest'='',STATUS,'$update_st_odprtih_mest'),
WHERE ID_TECAJA = $update_ID";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
header('Location: viv_settings_tecaji_main.php'); exit;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}$conn->close();
?>
A decent form example would be like the following
<form action='' method='post'>
<input type='text' name='field1' required>
<select name='fieldSelect'>
<option value='value1'>Value1</option>
<option value='value2'>Value2</option>
</select>
<input type='submit' name='send'>
</form>
then the PHP would be like
<?php
if(isset($_POST['send'] && (!empty($_POST['field1']) || !empty($_POST['fieldSelect']))){
$field1 = $_POST['field1'];
$fieldSelect = $_POST['fieldSelect'];
//YOUR SQL CODE
} else {
echo "Please Insert Some Data";
}
?>
In brief:
Give your Submit button a name
Check if the submit button is clicked or not by if(isset($_POST['submit-button-name'])){}
define your form's $_POST variables with names.
Continue with SQL.
There are a couple of ways you can avoid inserting "empty" records in your database. It depends if you want to do it in the client-side (before the form submits) or server-side (when the form is submitted to the server).
I'll show you how to do it server-side, since you posted your php script.
In viv_settings_tecaji.php
...
$update_status = $_POST['STATUS'];
$update_st_odprtih_mest = $_POST['st_odprtih_mest'];
$update_ID = $_POST['ID'];
if($update_status == "" || $update_st_odprtih_mest == "" || $update_ID == ""){
die("One of the form fields was empty");
}
...
That would kill your script if any of the form fields was empty. Potentially, you could check for null or use PHP's empty() function.
I hope this helps!
So i manege to get it to work using the following code. So for the part if user leaves both field empty i will put together a script for at least 1 to be required.
$sql = "UPDATE razpisani_tecaji
SET
STATUS = IF(LENGTH('$update_status')=0, STATUS, '$update_status'),
ST_ODPRTIH_MEST = IF(LENGTH('$update_st_odprtih_mest')=0, ST_ODPRTIH_MEST, '$update_st_odprtih_mest')
WHERE ID_TECAJA = $update_ID";

How to UPDATE only filled input with a submit button?

PROBLEM: I got a problem updating my input into sql using PHP, the PHP updates all empty values into sql which I don't want to.
ACHIEVEMENT: So I hope to achieve when user submit their data either empty or filled then PHP might be able to pickup and update only filled data into my sql. I tried using input with value=">php echo here<" but it won't work with textarea, so I couldn't find any solution since I'm new to PHP and SQL. Tried to find similar posts but I couldn't make them work like I wanted to :(
<?php include 'config/sqlconnect.php'; ?>
<form method="post" action"config/sqlconnect.php">
</p>MainPage info</p>
<input type="text" name="mainPageInfo"/>
<br>
</p>MiddlePage info</p>
<textarea name="middlePageInfo"></textarea>
<br>
</p>Container info</p>
<input type="text" name="containerInfo"/>
<br>
</p>Content</p>
<input type="text" name="content"/>
<br>
</p>Second content</p>
<input type="text" name="secondContent"/>
<input type="submit" name="submit" class="btn-block"/>
<br>
</form>
in PHP script
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "pagesDb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$sql = "SELECT * FROM myPages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$mainPageInfo = $row['mainPageInfo'];
$middlePageInfo = $row['middlePageInfo'];
$containerInfo = $row['containerInfo'];
$content = $row['content'];
$secondContent = $row['secondContent'];
}
} else {
echo "0 results";
}
if (isset($_POST['submit'])) {
$mainPageInfo = $_POST['mainPageInfo'];
$middlePageInfo = $_POST['middlePageInfo'];
$containerInfo = $_POST['containerInfo'];
$content = $_POST['content'];
$secondContent = $_POST['secondContent'];
$sql = "UPDATE myPages SET mainPageInfo='$mainPageInfo',
middlePageInfo='$middlePageInfo',
containerInfo='$containerInfo',
content='$content',
secondContent='$secondContent'
WHERE id=0";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Second Attempts: It doesn't update my data somehow... please help I tried more than 8 hours with no results :(
if (isset($_POST['submit'])) {
foreach($_POST as $name => $value) {
$sql = "UPDATE myPages SET $name = '$value' WHERE id=1";
}
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
Help would be appreciated, thanks everyone!
Using your Second Attempt as a starting point.
The problem with just using the POST array without being specific is that, in this example you are going to try an update a column on the database called submit i.e. your submit button. Later there may be data on the page that belongs in 2 or more tables.
So create an controlling array containing all the field names from the form that you want to process onto your table.
$db_fields = array('mainPageInfo', 'middlePageInfo', 'containerInfo',
'content', 'secondContent');
$sql = ''; // will hold the query we build dynamically
// was this a user sending data
if ( $_SERVER['REQUEST_METHOD' == 'POST' ) {
foreach($db_fields as $fieldname) {
if ( ! empty($_POST[$fieldname] ) {
$sql .= "$fieldname = '{$_POST[$fieldname]}', ";
}
}
}
$sql = rtrim($sql, ','); // remove the trailing comma
$sql = "UPDATE myPages SET $sql WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

Return PHP/MySQL results in HTML form for editing

I have a database that users can search by any number of predetermined fields (chosen from a drop down). The problem I'm having is being able to edit existing records. The first script prompts for the record ID to edit. If no record is found the user is told to try again.
When a record is found the results are suppose to display in HTML input boxes. The user can then modify the data, hit submit and the record updates (another script).
Enabled errors. This is what is thrown:
Fatal error: Call to undefined method mysqli_result::fetch__assoc() in (path to script) on line 37
Any ideas on what is wrong?
<?php
//Include everything but the password to connect to db
include 'includes/connect_pw.php';
//User supplies password on previous form
$dbpass = $_POST['password'];
//User supplies id on previous form
$rec_id = $_POST['query'];
//Create connection to database using mysqli
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
//Check connection. If error then kill process, show error and tell user to retry
if ($conn->connect_error) {
die ("<br><br>" . $conn->connect_error . "<p></p>Did you forget the password?");
}
//If no error then set select statement as variable
$sql = "SELECT * FROM dcr_master
WHERE (`ID` = '".$rec_id."')";
//Pass select ($sql) into connection ($conn) with result to ($result)
//Set new variables to populate input boxes. ex: $variable = $row['record field']
$result = $conn->query($sql);
if ($result->num_rows >=1) {
while ($row = $result->fetch__assoc()) {
$Server_Name = $row['Server_Name'];
$Description = $row['Description'];
$IP_Address = $row['IP_Address'];
$Wiki_Link = $row['Wiki_Link'];
}
?>
<form action="modify_dcr_3.php" method="POST">
<input type="hidden" name="ID" value="<?=$rec_id;?>">
Server Name<input type="text" name="Server_Name" value="<?=$Server_Name;?>">
Description<input type="text" name="Description" value="<?=$Description;?>">
IP_Address<input type="text" name="IP_Address" value="<?=$IP_Address;?>">
Wiki_Link<input type="text" name="Wiki_Link" value="<?=$Wiki_Link;?>">
<input type="submit">
</form>
<?php
}
else {
echo "<rb><br>No matching ID found.
<p></p>Try again. Just don't use " .$rec_id. " OK?";
}
?>
You have a double underscore on fetch__assoc(), this should have only a single underscore: fetch_assoc(). Specifically change this:
while ($row = $result->fetch__assoc()) {
...
}
To:
while ($row = $result->fetch_assoc()) {
...
}

select data from DB and Insert new data in front of selected row

I want to insert a data into a mysql database, but I need to put some constrains over that insertion. And my code is not working for me.
Basically I have selected "departments" from the mysql db using html select tag and show that in dropdown. And now I want to insert subject and subject code in front of that row which is selected in the drop down. But the problem is my code is not working and show me error please help and checkout code.
This is code for inserting data from mysql database. It work's fine.
<code>
<select class="form-control" name="department">
<?php
$host="localhost";
$username = 'root';
$password = "";
$con = mysql_connect($host,$username,$password);
mysql_select_db('sims',$con);
// Checking connection
if (!$con){
echo ("Failed to connect to MySQL:. " .mysql_error($con));
}
else {
echo("db connect");
}
$result = mysql_query("SELECT * from `sims-reg-department`");
if($result == FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_array($result)){
?>
<option value="<?php '.row[dept-id];'?>"><?php echo $row["dept-name"];?></option>
<?php }
?>
</select>
</code>
This section is showing me errors:
<code>
<?php
if(isset($_POST['submit'])){
$dptname = $_POST["department"] or
$coursename = $_POST["course-name"] and
$coursecode = $_POST["course-code"];
if($coursename=="" or $coursecode=="" )
{
echo "Please fill all the fields before hit submitting button";
return true;
}
else
{
$q = "INSERT INTO `sims-reg-department`(`course-name`,`course-code`)VALUES ('$coursename','$coursecode') where '$dptname' LIKE `dept-name`";
}
$res = mysql_query($q) or die(mysql_error());
mysql_close($con);
}
?>
</code>

Categories