mysql updating data only where post contains data - php

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";

Related

Trouble with PHP updating a database

Can I please have some help with a problem I'm having updating a mysql database with PHP.
I'm sorry to ask a question that has been asked a lot of times before, it's just driving me a bit nuts, and I've looked through similar questions but the answers don't seem to help with my problem.
I'm using two files, an admin page (admin.php) to edit content with, and an update file that is meant to update the database when the submit button is pressed.
Everything seems to be working fine, the values are being posted to the update.php page (I can see them when I echo them out) but it wont update the database.
If anyone can please point me in the right direction or tell me what I'm doing wrong I'd be very grateful!
Thank you very much:)
This is my admin.php page;
<head>
<?php
/*
Check to see if the page id has been set in the url.
If it has, set it as the $pageid variable,
If it hasn't, set the $pageid variable to 1 (Home page)
*/
if (isset($_GET['pageid'])) {
$pageid = $_GET['pageid'];
}
else {
$pageid = '1';
}
//Database connection variables
$servername = "localhost";
$username = "root";
$password = "";
$database = "cms";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Get information from the database
$sql = "SELECT title, sub_title, tab1, tab2, tab3, content FROM data WHERE id='$pageid'";
$result = $conn ->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) {
$conn->close();
//Store database information in variables to display in the form
$title = $row["title"];
$sub_title = $row["sub_title"];
$tab1 = $row["tab1"];
$tab2 = $row["tab2"];
$tab3 = $row["tab3"];
$content = $row["content"];
}
} else {
echo "0 results";
}
?>
</head>
<body>
//basic navigation
Page 1 | Page 2 | Page 3
<form action="update.php" method="post" name="adminform">
<input type="hidden" name="pageid" value="<?php echo "$pageid";?>">
NAME:<br>
<input type="text" name="title" value="<?php echo $title;?>"><br><br>
EMAIL:<br>
<input type="text" name="sub_title" value="<?php echo $sub_title;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab1" value="<?php echo $tab1;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab2" value="<?php echo $tab2;?>"><br><br>
CONTENT:<br>
<input type="text" name="tab3" value="<?php echo $tab3;?>"><br><br>
CONTENT:<br>
<textarea rows="4" cols="50" name="content">
<?php echo $content;?>
</textarea>
<br><br>
<input type="submit">
</form>
</body>
And this is the update.php page;
<?php
/*Values passed from the admin form, to be used as update variables*/
if (isset($_POST['adminform']))
{
$pageid = $_POST["pageid"];
$titleu = $_POST["title"];
$sub_titleu = $_POST["sub_title"];
$tab1u = $_POST["tab1"];
$tab2u = $_POST["tab2"];
$tab3u = $_POST["tab3"];
$contentu = $_POST["content"];
}
?>
<?php
if(isset($_POST['adminform']))
{
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Update the database
$sql = "UPDATE data SET title='$titleu', sub_title='$sub_titleu', tab1='$tab1u', tab2='$tab2u', tab3='$tab3u', content='$contentu' WHERE id =='$pageid'";
$result = $conn ->query($sql);
$conn->close();
}
?>
You're using == instead of = on the where clause.
On the other hand, don't pass user values to the query without validation and sanitization if you don't want to be vulnerable to sql injection attacks.
$sql = "UPDATE data SET title='" . $conn->real_escape_string($titleu) . "', sub_title='" . $conn->real_escape_string($sub_titleu) . "', tab1='" . $conn->real_escape_string($tab1u) . "', tab2='" . $conn->real_escape_string($tab2u) . "', tab3='" . $conn->real_escape_string($tab3u) . "', content='" . $conn->real_escape_string($contentu) . "' WHERE id = " . (int)$pageid;
This will work, but is not very elegant solution. You may use prepared statements instead, to pass the correct types and prevent sql injection.
Check your DB Connections and test whether you are connected to DB or not.
Change your query as below
$sql = "UPDATE data SET title='".$titleu."', sub_title='".$sub_titleu."', tab1='".$tab1u."', tab2='".$tab2u."', tab3='".$tab3u."', content='".$contentu."' WHERE id ='$pageid'";

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;
}

Getting value from dropdown and use it in query

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';";

How do I get a value from dynamically created form in a dropdown menu using PHP?

I'm trying to build an application that will direct a user to a different website based upon what zip code they enter. In order to narrow it down, in some instances, a user may need to select from a dynamically created drop down list of street names. The application uses PHP and a mySQL database. The issue that I'm having is detailed in the code comments under the PHP section. If possible, please provide a PHP driven solution. If jQuery, Javascript, AJAX, etc. are the only alternatives, please give me some example of how I would implement it with this example. Thanks!
Here's a snippet of the HTML:
<div id="mybox">
<form method="post">
<input type="text" name="zipcode">
<input type="submit" value="Enter Zip Code" name="submitzip">
</form>
</div>
Here is the PHP called by clicking the Submit button:
<?php
if (isset($_POST['submitzip'])) {
ZipLookup(); }
function ZipLookup() {
$zipcode = $_POST["zipcode"];
$zipcode = trim($zipcode);
if (strlen($zipcode) != 5) {
echo ("<strong>Please enter a valid five digit Zip Code.</strong>");
}
else {
$servername = "ip here";
$username = "username here";
$password = "password here";
$dbname = "dbname here";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ZipCode, StreetName, URL FROM db table here WHERE ZipCode ='$zipcode'";
$result = $conn->query($sql);
if ($result->num_rows > 1) {
echo '<hr><p><strong>We service more than one area in ' .$zipcode. '. Please select your street name.</strong></p>';
echo '<form method="post">';
echo '<select name="streetname">';
while($row = $result->fetch_assoc()) {
echo '<option value="' . $row["URL"] . '">' . $row["StreetName"] . '</option>';
}
echo '</select> <input type="submit" value="Submit" name="submitname"> </form>';
echo '<p>If your street name is not listed, please contact us.</p>';
// THIS IS WHERE I HAVE PROBLEMS... Values from dropdown don't appear to be stored. When running var_dump, PHP exports the array from the first button. Clicking the dynamic submit button just reloads the page.
if (isset($_POST['submitname'])) {
$url = $_POST["streetname"];
wp_redirect($url); }
}
elseif ($result->num_rows == 1) {
while($row = $result->fetch_assoc()) {
$url = $row["URL"];
wp_redirect($url);}
}
else {
echo '<strong>We do not provide service to this area.</strong>';
$conn->close();
}
}
}
?>
The second form is posting back to this page and it doesn't appear the zip code is being passed with the second form

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()) {
...
}

Categories