I have been having problems with a form of an website of mine. The form values are equal to their corresponding $_POST values, which are the parameters used for updating the database.
I do not want for empty form values to be updated. However, I don't want any of the input areas to be obligatory.
That means that I would be able to update only specific content, not needing to type the values in the input areas I do not want to update. I'm having problems with this, however. Empty form values are being uploaded, so the values in the database are being changed into blank values. I've looked for tutorials in SO and over the internet, and the only (functional) ones are those which turn input boxes into obligatory. That is not how I intend it to work, so it doesn't fit.
I think the best way to do this, and I am not sure, is to change, through javaScript, the "name" attribute of the input areas into blank when the submit button is set IF the values equal empty or null. I do not know how to do this, nor do I know if this is possible, or the best way.
Here is my current code on the matter:
(first, the form an the javascript)
<script>
function validade(){
var formId = document.getElementById("configForm");
var allInputs = formId.getElementsByTagName("input");
var input, i;
for (i=0; input = allInputs[i]; i++){
if (input.value == null || input.value == "") {
input.name = "";
}
}
}
<form method="post" action="" id="configForm">
<label for="home">Home:</label>
<br>
<input type="text" id="home" name="home">
<br>
<label for="apendix">Apêndice:</label>
<br>
<input type="text" name="apendix">
<br>
<label for="about">Sobre:</label>
<br>
<input type="text" name="sobre">
<br>
<label for="contato">Contato:</label>
<br>
<input type="text" name="contato">
<br><br>
<input type="submit" value="Carregar" name="submit">
</form>
<?php require_once('editaForma.php'); ?>
(Secondly, the database query and $_POST values:)
<?php //credentials
if (isset($_POST["submit"])){
$server = 'hypotetical';
$user = 'hypotetical';
$pw = 'hypotetical';
$BD = 'hypotetical';
//estabelece a conexão
$conn = mysqli_connect($server, $user, $pw, $BD);
if (!$conn) {
die ('<span style="color: #FF0000;">"connection failed: "</span>' . mysqli_connect_error());
}
$home = $_POST["home"];
$apendix = $_POST["apendix"];
$sobre = $_POST["sobre"];
$contato = $_POST ["contato"];
$query = "UPDATE form SET
home= '$home',
apendix= '$apendix',
sobre= '$sobre',
contato= '$contato'
WHERE id='1'";
//$query = "INSERT INTO form (home, apendix, sobre, contato) VALUES ('$home', '$apendix', '$sobre', '$contato')";
if (mysqli_query($conn, $query)){
echo "Alterações feitas com sucesso";
} else {
echo "ERRO!" . $query . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
Yes, I know the DB is prone to SQL injection. I'm trying to get everything up and running first, and once all of this is set, I'll look onto security matters before the website is online.
I've been having this problem for over a week and can't figure a way out of it.
Thank you for your time and attention, in advance.
EDIT
I wish I could select two answers for the solving ones. Both of them right down led me to the solving of the problem, each helping me to see the holes in my code. As I cannot choose both, I chose the one who helped me to solve the last issues. Thank you all so much!
Build your query dynamically, by skipping empty values
$p = &$_POST; //make $p refer to $_POST
$query = "UPDATE from SET ";
if($p['home']) $query .= " home = '$p[home]' ,";
if($p['apendix']) $query .= " apendix = '$p[apendix]' ,";
if($p['sobre']) $query .= " sobre = '$p[sobre]' ,";
if($p['contato']) $query .= " concato = '$p[contato]' ,";
$query = trim($query, ','); //remove any trailing comma
$query = "WHERE id = 1";
you can then execute the query. Oh and don't forget to check that at least 1 of the variables was available. If they're all empty, don't execute.
And yeah, your code is highly vulnerable.
Glaring security holes aside, I would usually build up a string, something like this:
$home = $_POST["home"];
$apendix = $_POST["apendix"];
$sobre = $_POST["sobre"];
$contato = $_POST ["contato"];
$query = "UPDATE form SET ";
if(!empty($home)) {
$query .= "home= '$home',";
}
if(!empty($apendix)) {
$query .= "apendix= '$apendix',";
}
if(!empty($sobre)) {
$query .= "sobre= '$sobre',";
}
if(!empty($contato)) {
$query .= "contato= '$contato',";
}
// strip off any extra commas on the end
$query = rtrim($query, ',');
$query .= "WHERE id='1'";
Building the query with the comma at the end also allows you to easily add more options later if you need to.
I did it, in a simple way using NULLIF
set potato = NULLIF(potato,'')
Related
I've asked once but I didn't get the answers.
var phoneno = /^\+?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
this is how I learnt to validate the numbers + error and...
I also have the Mobile bigint(20) & country varchar(200), in my table "users".
what I want to do is to use another file "countries.php" to get their codes in mobile input in "signup.php" page and store them both into the database.
for example, user chooses 'US +1' the country code will appear in mobile section.
$countryArray = array(
'AD'=>array('name'=>'ANDORRA','code'=>'376'),
'AE'=>array('name'=>'UNITED ARAB EMIRATES','code'=>'971'), ...
function countrySelector($defaultCountry = "", $id = "", $name = "", $classes = ""){
global $countryArray; // Assuming the array is placed above this function
$output = "<select id='".$id."' name='".$name."' class='". $classes."'>";
foreach($countryArray as $code => $country){
$countryName = ucwords(strtolower($country["name"])); // Making it look good
$output .= "<option value='".$code."' ".(($code==strtoupper($defaultCountry))?"selected":"").">".$code." - ".$countryName." (+".$country["code"].")</option>";
}
$output .= "</select>";
return $output; // or echo $output; to print directly
}
not to mention I downloaded the file zip. and I don't really know how to add or use the " use", please be more specific, like give with examples. thanks
I have run into a problem and Im not sure where to start... So my problem is- I need to use a dropdown which is automatically populated by a query concatenating two fields to make a single full-name. Then based off the name of the person selected change the value of the text input to be the dob, then also update every change when a new name selected. I have tried using the onchange event for select but just cant work out the right combination.
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database') or die ('Cannot connect to db');
$result = $conn->query("SELECT id, dob, CONCAT(`space`,`firstname`,`lastname`) AS `whole_name` FROM `table`");
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
$data = $id
unset($id, $name);
$id = $row['id'];
$name = $row['whole_name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
?>
<input type="text" id="text" value="<?php echo "$data" ?>"/>
Things to note - due to the concatenate needing a separator 'space' has been added to a field. at this time the sql query works exactly as intended. When loading the page in the current state the text field comes up with the correct value for the first name, but does not update when changing value of select.
Im new with PHP and mySQL - self learning as I go. Any help appreciated.
Ajax not needed here. You can just put the dob value as special attribute for each options, and then change the text input with javascript when the select value change.
Here the new select with dob in attribute :
while ($row = $result->fetch_assoc()) {
$data = $id
unset($id, $name);
$id = $row['id'];
$dob = $row['dob'];
$name = $row['whole_name'];
echo '<option dob="'.$dob.'" value="'.$id.'">'.$name.'</option>';
}
and then update the input when the select change, here an example with jquery :
$("select[name=id]").change(function(event) {
//get the dob attribute
var dob = $('option:selected', this).attr('dob');
// update the text input
$("input#text").val(dob);
});
I am attempting to submit a form immediately after a selection is made from a drop-down menu. After the form is submitted I want to send a query to a MySQL database based on the selection from the drop-down and display the retrieved text.
Currently, with what I have below, nothing is displayed, no errors are thrown. The JS submit event handler works but after the page reloads the new text is not displayed.
Any help is greatly appreciated.
The JS for submitting the form:
$(".platformSelectDropDown").change(function() {
$('.platformSelectForm').submit();
});
PHP to run after the form is submitted:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$platform = $_POST['platformSelectDropDown'];
$description = call_data($tableName, $platform)['Description'];
$application = call_data($tableName, $platform)['Application'];
}
PHP Function for querying and returning the data:
function call_data($tableName, $col, $platformName) {
include('connection.php');
$sql = 'SELECT * FROM $tableName WHERE platform_name = $platformName';
try {
return $db->query($sql);
}
catch (Exception $e) {
echo "Error! " . $e->getMessage() . "<br/>";
return array();
}
}
The Form:
<form class="platformSelectForm" method="post" action="index.php">
<select name="platformSelectDropDown" class="platformSelectDropDown">
...
</select>
<ul class="indent">
<li><?php echo($description); ?></li>
<li><?php echo($application); ?></li>
</ul>
</form>
I believe the code below will do what you want, with some improvements in security and functionality. However, please note that it's not clear to me from your code where $tableName is being set, so I just hard-coded that to be my test table. I intermingled the php and html, because it made it easier for me to work through the problem and I think it will make it easier for you to follow my solution. There's no reason why you can split it back out and functionize the php portions, similar to your original approach, if you prefer. Check it out:
<html>
<body>
<form class="platformSelectForm" id="platformSelectForm" method="post">
<?php
// Get which dropdown option is selected, if any, so can keep selected on page reload
if(!isset($_POST['platformSelectDropDown'])) {
// Not postback, default to first option ("Select One")
$p0Select = ' selected';
$p1Select = '';
$p2Select = '';
} else {
// Is postback
// Set variables for query below
$tableName = 'tbl_platforms_1';
$platformName = $_POST['platformSelectDropDown'];
// set dropdown selection to whatever was select at form submission
if($platformName == 'Platform_1') {
$p1Select = ' selected';
} elseif ($platformName == 'Platform_2') {
$p2Select = ' selected';
} else {
$p0select = ' selected';
}
}
?>
<select name="platformSelectDropDown" class="platformSelectDropDown" onchange="document.getElementById('platformSelectForm').submit()">
<option value="Select_One"<?php echo $p0Select; ?>>Select One</option>
<option value="Platform_1"<?php echo $p1Select; ?>>Platform 1</option>
<option value="Platform_2"<?php echo $p2Select; ?>>Platform 2</option>
</select>
<?php
// If dropdown value is set and does not equal "Select_One"
if(isset($_POST['platformSelectDropDown'])&& $_POST['platformSelectDropDown'] != 'Select_One') {
?>
<ul class="indent">
<?php
try {
// Set database parameters
// Replace these values with appropriate values for your database
// (okay to use an include like you did originally)
$dbhost = 'your_database_host';
$dbname = 'your_database_name';
$dbuser = 'your_database_user';
$dbpass = 'your_database_user_password';
// Create PDO
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare SQL statement and bind parameters
$stmt = $conn->prepare("SELECT * FROM $tableName WHERE platform_name = :platformName");
$stmt->bindValue(':platformName', $platformName, PDO::PARAM_STR);
// Execute statement and return results in an associative array (e.g., field_name -> value)
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Close Connection
$conn = null;
// For each row that was returned, output results
for ($i = 0; $i < count($results); $i++) {
echo '<li>' .$results[$i]['Description'] .'</li>';
echo '<li>' .$results[$i]['Application'] .'</li>';
}
} catch (Exception $e) {
echo '<li>Error! ' .$e->getMessage() . '</li>';
}
?>
</ul>
<?php
};
?>
</form>
</body>
</html>
Code I used to setup test:
DROP TABLE IF EXISTS tbl_platforms_1;
CREATE TABLE IF NOT EXISTS tbl_platforms_1 (
id int AUTO_INCREMENT NOT NULL,
platform_name varchar(20),
Description varchar(20),
Application varchar(20),
PRIMARY KEY (id)
);
INSERT INTO
tbl_platforms_1
(platform_name, Description, Application)
VALUES
('Platform_1', 'Description 1', 'Application 1'),
('Platform_2', 'Description 2', 'Application 2');
If this solves your problem, please remember to mark as answered, so everyone will know you no longer need help (and so I'll get rewarded for the hour I spent coming up with this solution :-). If this doesn't solve your problem, please provide as much detail as possible as to how the current results differ from your desired results and I will try to revise it to fit your needs. Thanks!
I have a form and I have been developing this website with my localhost and it is working perfect. But when I moved the files to my dedicated server it no longer gets any of the values when I submit the form. I have narrowed it down to two things. A either my server has restricted configurations on the form being submitted but I do not use global variables to get the values so that shouldnt be the problem or the php on the server is older and not allowing me to submit the values the server version i found out is <5.6. Here is my form code:
<form id="company-form" action="scripts/create-library.php" method="post" enctype="multipart/form-data">
<button id="hide-form"><img src="images/minus.png"/></button>
<h3>Add Library Item Form</h3>
<input class="c-name" type="text" name="file-display-name" placeholder="File Display Name"/>
<select class="companies-dd" name="companies">
<?php
require_once("../../scripts/connection.php");
// Select all companies and related data
$sql = "SELECT company_id, company FROM companies ORDER BY company_id";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result($c_id, $c);
while($stmt->fetch()){
echo "<option value='".$c_id."'>".$c."</option>";
}
?>
</select>
<select class="companies-dd" name="library-cats">
<?php
// Select all companies and related data
$sql = "SELECT library_category_id, library_category FROM library_categories ORDER BY library_category_id";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result($l_id, $l);
while($stmt->fetch()){
echo "<option value='".$l_id."'>".$l."</option>";
}
$conn->close();
?>
</select>
<input id="uploadFile" class="image-name" type="text" name="library-file-name" placeholder="No Logo File Chosen" disabled="disabled"/>
<input id="uploadBtn" type="file" name="library-file"/>
<input type="submit" value="Create Item"/>
</form>
This is added the page via ajax call on a button click.
Then the script that I run after the form is submitted is
<?php
session_start();
ini_set('display_errors',1);
error_reporting(-1);
$display = trim($_POST["file-display-name"]);
$company = trim($_POST["companies"]);
$lib_cat = trim($_POST["library-cats"]);
if(empty($display) || empty($company) || empty($lib_cat)){
$_SESSION["errormsg"] = "Required information is missing please fill out all required fields.";
header("Location: ../library.php");
}
else{
$file_name = $_FILES['library-file']['name'];
$tmp_name = $_FILES['library-file']['tmp_name'];
$file_size = $_FILES['library-file']['size'];
$file_type = $_FILES['library-file']['type'];
$fp = fopen($tmp_name, 'r');
$content = fread($fp, filesize($tmp_name));
$content = base64_encode($content);
fclose($fp);
if(!get_magic_quotes_gpc()){
$file_name = addslashes($file_name);
}
if(empty($content)){
$_SESSION["errormsg"] = "Required information is missing please fill out all required fields (File).";
header("Location: ../library.php");
}
else{
require_once("connection.php");
// Insert the logo into the companies photo table
$sql = "INSERT INTO library_items(filename, mime_type, file_size, file_item, display_name, company_id, library_category_id) VALUES(?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sssssss', $file_name, $file_type, $file_size, $content, $display, $company, $lib_cat);
if(!$stmt->execute()){
$_SESSION["errormsg"] = "Failed to add library item: ".mysqli_error();
header("Location: ../library.php");
}
}
unset($_SESSION["errormsg"]);
$_SESSION["successmsg"] = "Library Item successfully added into the database.";
header("Location: ../library.php");
}
?>
It gives me the errors with the variables saying that they are undefined index's for the form names.
I have read other posts but none of them has helped me. Is there something I am not seeing or I have to change on my server for me to use this?
Well it looks like the two files I had for testing the upload and display ended up corrupt when I downloaded them. This was causing the server to throw and error saying that the text was outside the US-ASCII range. Since this was not able to be display it didnt transfer any of the forms values. That was the weirdest bug I ever had I guess I will have to start testing my pdfs for errors also.
I have created a comment-reply system in php. It is similar to wall in facebook. User writes a comment and then post it in "wall". I use the following tables in my database to hold comments: comments(comments_id, comment, comment_date, user, comment_hash, flash) and table users that hold user's details: users(user_id, name, surname). Everything works perfect, the only problem is that I cannot delete a certain comment. Deleting a comment means to set flag=1 for this comment in my database.
On each comment there is a link named "delete". When user press delete, a light box starts in javascript and user by pressing delete, the function "deletepost" is executed. My only problem is that this function sets flag=1 to all comments in my databe and not for the certain comment that I press delete. Any idea how to improve my code?
I use the following function in order to display comments:
<?php
function getComments(){
$session_user_id = $_SESSION['user_id'];
$comments = "";
$sql = mysql_query("SELECT * FROM comments WHERE (`flag`=0) ORDER BY comment_date DESC LIMIT 40") or die (mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'> Write your first posts ...</div> ";
}
else{
while ($row= mysql_fetch_assoc($sql)) {
$comment_id = $row['comments_id'];
$hash = $row['comment_hash'];
$personal_1 = mysql_query("SELECT `user_id`, `name`, `surname`, `email`, `profile` FROM `users` WHERE `user_id`='{$row['user']}' ");
while ($run_personal_1= mysql_fetch_assoc($personal_1)) {
$comment_user_id = $run_personal_1['user_id'];
$comment_user_name = $run_personal_1['name'];
$comment_user_surname = $run_personal_1['surname'];
}
// displays comment that includes user's name and surname and hash
$comments .= " $comment_user_surname $comment_user_name $hash";
$comments .= ".$row['comment'].";
//---- at this point I insert a delete link , that when user presses it a javascript light box ask user if wants to delete the comment. If user press the delete button it is called the function named "deletepost".
//---- first checks if the comment is from the user that is logged in ($session_user_id) in order to have the right to delete post
if($comment_user_id == $session_user_id){
if(isset($_POST['submit_2'])) {
deletepost($session_user_id, $comment_id);
header('Location: wall.php');
}
$comments .= <<<EOD
<font color='grey' >Delete</font>
<div id="light" class="white_content">
<form action="$_SERVER[PHP_SELF]" method="post">
<input type="submit" name="submit_2" value="Delete Post ">
</form>
<button>Cancel</button>
</div>
<div id="fade" class="black_overlay"></div>
EOD;
}
}
return $comments;
}
?>
I use the following function in order to post comments:
<?php
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$session_user_id = $_SESSION['user_id'];
$random_num = rand(0, 99999999999);
$sql = mysql_query(" INSERT INTO `comments` (comment, comment_date, user, comment_hash) VALUES ('".$comment."', now(), '$session_user_id', '$random_num') ");
return getComments();
}
?>
I use the following function in order to delete comments. Deleting comments means that I set flag=1, and in my function that displays the comments (function getComments), if flag is equal to 1 I do not display this comment:
<?php
function deletepost($comment_user_id, $comment_id){
$get_hash = mysql_query("SELECT `comment_hash` from `comments` WHERE (`user`='$comment_user_id' AND `comments_id` = '$comment_id') ");
while ($run_hash= mysql_fetch_assoc($get_hash)) {
$hash = $run_hash['comment_hash'];
}
$sql="UPDATE `comments` SET `flag`=1 WHERE (`user`='$comment_user_id' AND `comment_hash`='$hash')";
$result=mysql_query($sql) or die("Error when trying to delete...");
}
?>
My first instinct is to guess that comment_hash isn't working quite right, for whatever reason. Try simplifying your delete function:
function deletepost($comment_user_id, $comment_id){
$sql="UPDATE `comments` SET `flag`=1 WHERE (`user`='$comment_user_id' AND `comments_id`='$comment_id')";
$result=mysql_query($sql) or die("Error when trying to delete...");
}
I'm not sure why your current delete function is querying your database to grab a hash from a table and then using the hash to find the same row from the same table. It seems pointless and inefficient, and introduces more things that can break.
Incidentally, Vascowhite is correct that you shouldn't be using the old mysql library, but I don't think changing that would fix your problem here.
In deletepost why did you run while loop to get the hash , if you are deleting one comment one time . Another thing is that flag=1 happens in all your comment because hash may be common for that users all comment . You need to make hash unique for every comment of a particular user .