Only update entry when there is a new value - php

I have a form that will update specified entries in a mysql table. The form will only submit if all the fields are filled in .
Is there a way to make it so that the form will only update fields that have a new value and leave the ones that have been left blank?
Form code :
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
if(isset($_POST['update']))
{
$con = mysql_connect($server, $db_user, $db_pass);
if(! $con )
{
die('Could not connect: ' . mysql_error());
}
$id = $_POST['id'];
$english = $_POST['english'];
$math = $_POST['math'];
$science = $_POST['science'];
$table = $_POST['year'];
$sql = "UPDATE $table ".
"SET english = $english ,math = $math ,science = $science ".
"WHERE id = $id" ;
mysql_select_db('education');
$retval = mysql_query( $sql, $con );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
//header("Location: " . $_SERVER['PHP_SELF']);
//echo "Entered data successfully\n";
mysql_close($con);
}
else
{
?>
<?php } ?>
<h4 align="center">Update student details</h4>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
Student ID:
<input name="id" type="text" id="id">
<br>
English mark:
<input name="english" type="number" id="english">
<br>
Math's mark:
<input name="math" type="number" id="math">
<br>
Science mark:
<input name="science" type="number" id="science">
<br>
Year: <br>
<select name="year" id="year">
<option value="">Select...</option>
<option value="year1">Year 1</option>
<option value="year2">Year 2</option>
<option value="year3">Year 3</option>
<option value="year4">Year 4</option>
</select>
<br>
<br>
<input name="update" type="submit" id="update" value="Submit">
</form>

use isset() before use the variables in your query

try this :
$sql = "UPDATE $table ".
"SET english = $english ,math = $math ,science = $science ".
"WHERE id = $id AND (english != $english OR math != $math OR science != $science)";

Related

Dynamic dropdown for a webpage is not populating from my database

I cannot figure out why the dynamic dropdown won't populate from my database.:
<!doctype html>
<html>
<body>
<h2>Insert Album</h2>
<form action="insertalbum.php" method="POST">
Title: <input type="text" name="atitle" maxlength='50' required><br>
Band: <select name='bands'>
<?php
$conn = mysqli_connect("Server","database","password","username"); //i put in these placeholder for my actual credentials
// Check connection
if(mysqli_connect_errno()){
echo nl2br("Failed to connect to MySQL: " . mysqli_connect_error() . "\n ");
}
$query = "SELECT DISTINCT name FROM band";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
unset($name);
$name = $row['name'];
echo '<option value="name"> $name </option>';
}
?>
</select>
<br>
Published Year: <input type="number" name="pyear" min='1900' max='2020' required><br>
Publisher: <input type="text" name="pname" maxlength='50' required><br>
Format:<select> <option value="record"> Record </option>
<option value="cd"> CD </option>
<option value="casette"> Casette </option>
</select> <br>
Price: <input type="number" name="price" min='0' max='9999.99'><br>
<input type="submit" value="Insert">
</form>
</body>
</html>
this a example:
<select id="employee">
<option value="" selected="selected">Select Employee Name</option>
<?php
/* connection */
$conn = mysqli_connect("Server","database","password","username");
/* query */
$sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee LIMIT 10";
/* get data from db */
$resultset = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
/* build your dropdown*/
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["id"]; ?>"><?php echo $rows["employee_name"]; ?></option>
<?php } ?>
</select>

Mysqli SELECT JOINS multiple WHERES

I have a problem with multiple wheres in a consult to database mysqli. I don't know how to make it. I'm reading about JOINS for multiple consults, but I don't know it very well, and it still doesn't work. This is my code:
$status = mysqli_escape_string($con, $_POST['status']);
$type = mysqli_escape_string($con, $_POST['type']);
$beds = mysqli_escape_string($con, $_POST['beds']);
$baths = mysqli_escape_string($con, $_POST['baths']);
$query = "SELECT * FROM properties WHERE beds LIKE '%".$beds."%' OR baths LIKE '%".$baths."%' " ;
I need to obtain all results that have beds, baths, status, types, etc, but it does not work with the actual SELECT. I already made some tries with JOINS, but that did not work the way I expected. This function gives all the results but not filtered. Thank you for any help!
EDIT:
This is all my code, my form
<form action="" id="amenities-form" name="amenities-form" data-name="Amenities Form" class="top-search-form-left" method="POST">
<select id="status" name="status" data-name="status" class="select-search-form w-select">
<option value="sale">For Sale</option>
<option value="rent">For Rent</option>
</select>
<select id="type" name="type" data-name="type" class="select-search-form w-select">
<option value="">Type of property</option>
<option value="condo">Condo</option>
<option value="house">House</option>
<option value="commercial">Commercial</option>
<option value="lot">Lot</option>
<option value="villa">Villa</option>
<option value="business">Business</option>
<option value="fractional">Fractional</option>
<option value="boat">Boat</option>
</select>
<input type="text" class="input-search-form w-input" maxlength="256" name="beds" data-name="beds" placeholder="Beds" id="beds">
<input type="text" class="input-search-form w-input" maxlength="256" name="baths" data-name="baths" placeholder="Baths" id="baths">
<input type="submit" value="Go" class="btn-search-left w-button">
</form>
<form action="" id="search-form" name="search-form" data-name="Search Form" class="top-search-form-right" method="POST">
<input type="text" class="input-search-form w-input" maxlength="256" name="search" data-name="search" placeholder="Search..." id="search-word">
<input type="submit" value="Lupa" class="btn-search-right w-button">
</form>
This is my code of php
if (!empty($_POST)) {
$con = new mysqli($host, $user, $pass, $db);
if (mysqli_connect_errno()) {
printf("Falló la conexión failed: %s\n", $con->connect_error);
exit();
}
if (isset($_POST['search'])) {
$search = mysqli_escape_string($con, $_POST['search']);
$query = "SELECT * FROM properties WHERE title LIKE '%".$search."%'" ;
}else{
$status = mysqli_escape_string($con, $_POST['status']);
$type = mysqli_escape_string($con, $_POST['type']);
$beds = mysqli_escape_string($con, $_POST['beds']);
$baths = mysqli_escape_string($con, $_POST['baths']);
$query = "SELECT * FROM properties WHERE beds LIKE '%".$beds."%' OR baths LIKE '%".$baths."%' " ;
}
$res = $con->query($query);
if (!$res) {
trigger_error('Invalid query: ' . $con->error);
}
if ($res->num_rows) {
while ($row = $res->fetch_object()) {
//$status_name = $con->query("SELECT * FROM status WHERE id = {$row->status_id}");
//$status_name = $status_name->fetch_object();
//echo "{$row->title} ({$status_name->title})<br>";
echo "{$row->title} ({$row->status_id})<br>";
}
}else{
echo "No results";
}
$res->free();
$con->close();
}else{
echo 'No results';
}
I will try some suggest you did

php code to take values from two forms and insert it in table

I have two forms on one page. First one take names of students according to group. Second form is used to enter marks individually. Now i want to insert their marks but failed to do this. Kindly help me regarding this. My code is:
$faculty = null; //declare vars
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Not connected : ' . mysql_error());
}
mysql_select_db('Sims', $link) or die("cannot select DB");
if(isset($_POST["faculty"]))
{
$faculty = $_POST["faculty"];
}
?>
<script language="JavaScript">
function autoSubmit()
{
var formObject = document.forms['theForm'];
formObject.submit();
}
</script>
<form name="theForm" method="post">
<select name="faculty" onChange="autoSubmit();">
<option value="null"></option>
<option value="computer" <?php if($faculty == 'computer') echo " selected"; ?>>Computer</option>
<option value="commerce" <?php if($faculty == 'commerce') echo " selected"; ?>>Commerce</option>
</select>
<br><br>
<?php
if($faculty =='computer')
{
echo "<select name=\"name\">";
$sql = mysql_query("SELECT name FROM std_reg where faculty= 'computer' ") or die(mysql_error());
while($row = mysql_fetch_array($sql)){
echo "<option>".$row[name]."</option>";}
echo "</select>";
}
if($faculty =='commerce')
{
echo "<select name=\"name\">";
$sql = mysql_query("SELECT name FROM std_reg where faculty= 'commerce' ") or die(mysql_error());
while($row = mysql_fetch_array($sql)){
echo "<option>".$row[name]."</option>";}
echo "</select>";
}
?>
<br><br>
</form>
<form method="post">
math <input type="text" name="urdu" />
science <input type="text" name="science" />
social <input type="text" name="social" />
submit
</form>

How to use forms to update SQL

I'm trying to make a form that uses a drop down, radio buttons, text field, textarea, and a hidden value(the time) then takes that information from that form and updates SQL database.
My form is below and it all loads correctly but I'm having issues updating the values and trying to figure out how to make the radio buttons and dropdowns to work since I can't make the value php code and need to pass the value. Everything I'm finding on the web is how to do text fields where the user types something.
When I select update it just submits the data but nothing changes. On my update.php I have a sanitize function at the very end and am unsure how to pass the variables in. Do I create an array named $var and input all my variables into it or pass each variable at a time?
I've been searching the web for HOW TO's and am currently reading two books but they don't go into enough detail so thanks for any assistance.
control.php
<?php
session_start();
if( !isset($_SESSION['myusername']) ){ header("Location: login.php"); }
?>
<?php
require("../../system/templates/includes/constants.php");
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$connection) { die("Database connection failed: " .mysql_error()); }
$db_select = mysql_select_db(DB_NAME,$connection);
if(!$db_select) { die("Database selection failed: " . mysql_error()); }
?>
<form method="post" action="update.php">
<select name="name" required="true" value="<?php echo $row['name']; ?>">
<?php
$query="SELECT id, name FROM modules";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)) {
echo "<option value=\"" . $row['id'] . "\">" . $row['name'] . "</option>";
}
?>
</select>
<br />
Select Status:
Red <input type="radio" value="red" name="status" />
Yellow <input type="radio" value="yellow" name="status" />
Green <input type="radio" checked="checked" value="green" name="status" />
<br />
Reason:
<br />
<select name="reason" required="true">
<option value="0" selected="selected" value="">Select Reason</option>
<option value="ONLINE">Online</option>
<option value="MAINTENANCE">Maintenance</option>
<option value="ERROR">Error</option>
<option value="OFFLINE">Offline</option>
<option value="">No Reason</option>
</select>
<br />
ETA:
<br />
<input type="text" name="eta" value="<?php echo $row['eta']; ?>" maxlength="8" />
<br />
Description:
<br />
<textarea rows="5" cols="30" name="explanation" wrap="hard" required="true" maxlength="320" value="<?php echo $row['description']; ?>" /></textarea>
<br />
<div align="right">
<input name="update" type="submit" value="Update"/>
<input type="hidden" name="last_updated" value="<?php $mysqldate = date ('H:i'); $phpdate = strtotime ( $mysqldate );?> />
</form>
update.php
<?php
print_r(_POST);
if(isset($POST['update']))
{
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(! $connection)
{
die('Could not connect: ' .mysql_error());
}
$name = $POST['name'];
$status = $POST['status'];
$reason = $POST['reason'];
$eta = $POST['eta'];
$description = $POST['description'];
$last_updated = $POST['last_updated'];
$updated_by = $POST['updated_by'];
$sql = "UPDATE module SET status = $status , reason = $reason , eta = $eta , description = $description , last_updated = $last_updated , updated_by = $updated_by WHERE name = $name";
mysql_select_db('status');
$retval = mysql_query ( $sql, $connection);
if (!retval)
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully";
mysql_close($connection);
} else {
// not sure what to do here
}
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
function sanitizeMySQL($var)
{
$var = mysql_real_escape_string($var);
$var = satnizeString($var);
return $var;
}
header("Location: control.php");
?>
As always I greatly appreciate any assistance anyone can offer. I'm still in the very early stages of learning this and this website and community has helped me more than any book/tutorial I've read so far.
Your SQL statement needs quotation marks for each parameter.
$sql = "UPDATE module SET status = '$status' , reason = '$reason' , eta = '$eta' , description = '$description' , last_updated = '$last_updated' , updated_by = '$updated_by' WHERE name = '$name' ";
As for the sanitizeString() function, it only takes in one string at a time. Maybe something like the one below may be simple and clean:
$params = array($name, $status, $reason); // put all your params in here
foreach ($params as &$p) { // the '&' before $p is essential, so do not forget it
$p = sanitizeString($p);
}
Hope it helps.

advice on php post operation not running

I have donation page which when the user clicks donate it posts the data to a php file named test.php I am trying this out my first trying to echo the first name and last name but this is not working ultimately I want this php page to run a MySQL query to update the total_Donation row within a database, here is my main php page first.
Database code which sits at top of file
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
$names_sql = "SELECT first_Name, last_Name FROM donate WHERE user_ID > 0";
$names_query = mysql_query($names_sql)or die(mysql_error());
$rsNames= mysql_fetch_assoc($names_query);
if(isset($_POST['donation']) && $_POST['donation'] != '')
{
$donation = mysql_real_escape_string($_GET['donation']);
$fname = mysql_real_escape_string($_GET['first_Name']);
$lname = mysql_real_escape_string($_GET['last_Name']);
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + '{$donation}' WHERE first_Name = '{$fname}' AND last_Name = '{$lname}'";
}
mysql_close($con);
?>
Here is my form section of html
form method ="post" action="test.php">
<table>
<tr><td><label>Runner:</label></td>
<td>
<select>
<?php do{?>
<option> <?php echo $rsNames['first_Name'];?> <?php echo $rsNames['last_Name'];?></option>
<?php } while ( $rsNames= mysql_fetch_assoc($names_query))?>
</select>
</td>
</tr>
<tr><td><label>Donation £</label></td><td><input type="text" maxlength="9" value="0.00" name="donation"/></td></tr>
<tr><td><input id="submit" type="submit" value="DONATE"/></td></tr>
</table>
</form>
the option gets all the first names and last names fine when the user hits donate I want it to run the $donation_sql but all i get are errors saying unidentified index, I'm even trying the below in the test.php to simply just echo the first_Name this is giving the same error.
<?php
echo $_POST['first_Name'];
?>
Can someone please help me with this, thanks.
index.php
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
$names_sql = "SELECT first_Name, last_Name FROM donate WHERE user_ID > 0";
$names_query = mysql_query($names_sql)or die(mysql_error());
?>
<form method ="post" action="test.php">
<table>
<tr><td><label>Runner:</label></td>
<td>
<select name="name">
<?php
while($list = mysql_fetch_array($names_query))
{
?>
<option value="<?php echo $list['first_Name'] . ' ' . $list['last_Name']; ?>">
<?php echo $list['first_Name'] . ' ' . $list['last_Name']; ?>
</option>
<?php
}
?>
</select>
</td>
</tr>
<tr><td><label>Donation £</label></td><td><input type="text" maxlength="9" value="0.00" name="donation" /></td></tr>
<tr><td><input id="submit" type="submit" name="send" value="DONATE"/></td></tr>
</table>
</form>
test.php
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
if(isset($_POST['donation']) && $_POST['donation'] != '')
{
$names = explode(' ',$_POST['name']);
$first_name= $names[0];
$last_name= $names[1];
$donation = mysql_real_escape_string($_POST['donation']);
$fname = mysql_real_escape_string($first_name);
$lname = mysql_real_escape_string($last_name);
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + '" .$donation. "' WHERE first_Name = '" .$fname. "' AND last_Name = '" .$lname. "'";
echo 'DEBUG (remove after OK): <br>' .$donate_sql. '<br>';
$res = mysql_query($donate_sql);
echo 'Thanks ' .$first_name. ' ' .$last_name. '<br>';
}
mysql_close($con);
?>
That´s it!
\make sure you set name for select and you have valua attr in option tag
<select name="first_Name">
<otpion value="<?php echo $rsNames['first_Name'];?>"><?php echo $rsNames['first_Name'];?>
<?php echo $rsNames['last_Name'];?>
</option>
</select>
YOu need to give a name attribute to the select:
<select name="first_Name">
<?php while ( $rsNames= mysql_fetch_assoc($names_query)):?>
<option value="<?php echo htmlspecialchars($rsNames['first_Name']).' '.htmlspecialchars($rsNames['last_Name']);?>"> [option displayed to the user here]</option>
<?php endwhile;?>
</select>
And of course use the $_POST array, not the $_GET, since you're using the POST method.

Categories