Hi im trying to create a subscribe to mailing list widget. its kind of working but keeps adding a blank row after every insert. I would like to jsut be able to let users add their name and email address to 2 inputs and click submit, then the details should be saved into the database, avoiding spam and duplications etc.
here is where am at so far hopefully someone could give a few pointers im very new to php so any help is appreciated thanks!
<?php
// Connect to server and select database.
//mysql_connect("$subsc_hostname", "$subsc_username", "$subsc_password")or die("cannot connect");
//mysql_select_db("$subsc_database")or die("cannot select DB");
$mysqlconn= new PDO('mysql:dbname=' .$subsc_database . ';host=' . $subsc_hostname, $subsc_username, $subsc_password);
$subsc_name = $_POST['sub_FullName'];
$subsc_email = $_POST['sub_EmailAddress'];
// Insert data into mysql
$sql="INSERT INTO subscribers(subsc_name, subsc_email)VALUES('$subsc_name', '$subsc_email')";
$result=mysql_query($sql);
// close connection
mysql_close();
?>
<form method="post" action="">
<div class="form-group">
<label>Full Name:</label>
<input class="form-control" type="text" name="sub_FullName" />
<br>
<label>Email:</label>
<input class="form-control" type="text" name="sub_EmailAddress" />
<div class="pull-right">
<input type="submit" value="Subscribe" />
</div>
</div>
</form>
You may want to move the last } in your file:
} else {
mail( $to, $subject, $message, $headers );
echo "<div class='alert alert-success alert-dismissable'><h4>Subscribed!</h4><p>Thanks $contact_name,<br /><br />you will start receiving emails via $contact_email very soon.</div>";
// FROM HERE
// Insert data into mysql
$sql="INSERT INTO subscribers(subsc_name, subsc_email)VALUES('$subsc_name', '$subsc_email')";
$result=mysql_query($sql);
// TO HERE
}
To add to the comments to your question, you may want to take a look at lightweight frameworks like Silex and to database abstraction layers, like Doctrine. Using such tools, you greatly reduce the risks of SQL injections and you don't need to code every single user provided data control by hand.
Related
I am currently working on a form that uses PHP and SQL to update information in a database. It is functioning properly and updating the information but the issue is... is that it updates everything, including fields that I didn't even put any input in which means it will only update a particular row in the database and leave the others blanks... I need it to just change information from a field with an actual input and leave it if there is no input.
Here is the PHP and SQL code:
try {
$deleteRecId = $_GET['id'];
$update_event_name = $_POST['updateName'];
$update_event_location = $_POST['updateLocation'];
$update_event_date = $_POST['updateDate'];
include 'connect.php';
if(isset($_POST["submit"])) {
// new data
$sql = "UPDATE events SET event_name='$update_event_name',
event_location='$update_event_location', event_date='$update_event_date'
WHERE event_id=$deleteRecId";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and here if the form:
<form class="update-form" action="<?php echo $_PHP_SELF ?>" method="post">
<p id="input-headers">Event Name</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateName" value="">
</p>
<p id="input-headers">Event Location</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateLocation" value="">
</p>
<p id="input-headers">Event Date</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateDate" value="" placeholder="01/01/2000">
</p>
<input type="submit" name="submit" value="Submit" id="updateBtn">
</form>
So to sum up I need this application to only update information of a field with an actual input and if the form field has no input I need that database info to remain the same. I appreciate any help with this as I am pretty new to these concepts... thanks!
I found a really handy solution to this! Here is how I implemented it into my code.
$sql = "UPDATE events SET event_name=IF(LENGTH('$update_event_name')=0, event_name, '$update_event_name'), event_location=IF(LENGTH('$update_event_location')=0, event_location, '$update_event_location'), event_date=IF(LENGTH('$update_event_date')=0, event_date, '$update_event_date') WHERE event_id=$deleteRecId";
It basically just checks whether the string is empty or not. If it's empty it won't be updated. If it isn't empty it'll go through with the update! Very simple way to achieve this effect when creating an update form.
Using your current code structure, you can do this.
Use SQL to select * from event ID. Populate your update_event_xxx with the parameters.
If $_POST[xx] is blank, ignore. Else, update_event_xx = $_POST[xx]
Well I am pretty much trying to create database with some table, the values in the table and check them in phpMyAdmin. I am able to create the table and database, but not the values
2.) when I add the isset $_post['submit'] variable, when I click the submit button, nothing is getting created. Is there a syntax error I am not seeing?
<html>
<body>
<p> welcome to my Page
Please insert the data below
<br>
<br>
<form action="input.php" method="post">
<p> Name: <input type="text" name="name">
<p> Age: <input type="text" name="age">
<p> Address: <input type="text" name="address">
<p> Email: <input type="text" name="email">
<input type="submit" value="Send!" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
//connects to the sql database
$con = mysql_connect("localhost", "willc86", "tigers330");
if (!$con) {
echo 'can not connect to Database' . "<br>";
}
//creates the database in mySQL
$db = mysql_query("CREATE DATABASE form");
if (!$db) {
echo 'Did not create database';
}
//select the database and connect to it. on where you want to create tables.
mysql_select_db("form", $con);
//create the table once "form database" is selected
$table = "CREATE TABLE users (
Name varchar(30),
Age varchar(30),
Address varchar(30),
Email varchar(30)
)";
mysql_query($table,$con);
//insert the data from the form
$value= "INSERT INTO users (Name, Age, Address, Email)
VALUES ('$_POST[name]','$_POST[age]','$_POST[address]','$_POST[email]')";
mysql_query($value,$con);
mysql_close();
}//end of submit
?>
</body>
</html>
Your form action is input.php, is your file called input.php as well? Otherwise you'd be executing input.php when you're submitting the form instead of executing the PHP on your page.
I think user willc86 don't have access rights for create databases.
In second your script is incorrect, because it run for each "user add" operation and tried create database and table.
You can create it once in phpadmin and use in your script only insert.
No point in highlighting particular errors here as others are unlikely to have the exact same issue. Better to just give you the tools/means to debug the issue for yourself.
Instead of:
mysql_query($table,$con);
Try:
$res = mysql_query($table,$con);
if($res === false){
throw new Exception(mysql_error($conn));
}
Better yet, use PDO.
First of all your code is fine if this file name is input.php. There can be few reasons, one that you have incorrect credentials second that the user does not have a right to create table, for that go to Phpmyadmin and give user all rights.
Secondly and most importantly, use Prepared statements or mysqli otherwise you are vulnerable to SQL Injection
For that do go through this post
How can I prevent SQL injection in PHP?
I'm designing a crud app to store storage data in a database. Using php, mySQL (with the help of XAMPP). I keep running into this problem, though, where I click "Submit" on my form and the function appears to run successfully (I get a the success message on the php page), but when I look at the actual database, the row fills 3 of the fields (the first 1 and the last 2) with just "0" regardless of what's in the form when I click submit. And then the other two columns don't have anything in them at all.
Here's my code for the form:
<div id="newprojform">
<fieldset><legend>Create New Project</legend>
<form action='projectadded.php' name="addnewproject" onsubmit="return(validate());">
<div id="newprojfields"><br />
Project Name:
<div class="field">
<input type="text" name="projname" size="50">
</div>
<br /><br />
Customer:
<div class="field">
<input type="text" name="custname" size="50">
</div>
<br /> <br />
Move ID:
<div class="field">
<input type ="text" name="moveID" size="50">
</div>
<br /><br />
<label for="unit">Unit of Measurement: </label>
<div class="field" id="uomdd">
<select id="unit" name="unit">
<option value="Select">Select</option>
<option value="CWT">CWT</option>
<option value="Vault">Vault</option>
<option value="SqFt">SqFt</option>
<option value="Pallet">Pallet</option>
<option value="Piececount">Piece Count</option>
</select>
</div>
<br /><br />
Cost Per Unit:
<div class="field">
<input type="text" name="cost" size="50">
</div>
<br /> <br />
<input type="submit" value="Add Project" id="submit"><br />
</div>
</form></fieldset>
</div>
And here's the php
<?php
$con=mysqli_connect("localhost","root","", "storagelog");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO newproject (moveid, projectname, customername, UoM, PPU)
VALUES
('$_POST[moveID]','$_POST[projname]','$_POST[custname]','$_POST[unit]','$_POST[cost]')";
if(!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Can anybody please tell me what I'm doing wrong? I've gone over the syntax and names of the forms a million times, but every time I click "submit," I just get a row that either has zeros in it or nothing at all. This is all very new to me, so i'm expecting a lot of stupid or clunky mistakes, but this is the first time I'v ever been so stuck..
any help is appreciated.
The problem is that you aren't specifying POST as the method in your form, but you are trying to read the form variables from the $_POST variable. See this thread: What is the default form HTTP method? for information about the form defaults. To fix it, you just need to change your form to this:
<form action='projectadded.php' name="addnewproject" onsubmit="return(validate());" method="POST">
There are some other things you should change in here, like sanitizing your inputs before putting them into the database, but those aren't the root of your problem.
So first things first. I don't recommend using unfiltered $_POST and $_GET variables when dealing with the database (in a production setting of course).
Second, when using the form element, you have to specify whether you're using a post method, or a get method:
<form action="location_of_file.php" method="POST">
Also, make sure you check that your column names in the table absolutely match the names in your sql insert syntax.
Maybe even try the following to see if it inserts:
$sql="INSERT INTO newproject (`moveid`, `projectname`, `customername`, `UoM`, `PPU`)
VALUES ('" . $_POST["moveID"] . "','" . $_POST["projname"] . "','" . $_POST["custname"] . "','" . $_POST["unit"] . "','" . $_POST["cost"] . "')";
Sometimes, SQL can be touchy.
Lol, dang... seanmk beat me to the punch. If what we suggest works, choose his answer as he was first to post it.
For future reference (aside from the excellent advice in the other answers) you should consider printing out $sql to see what your actual insert statement looks like. You'd see immediately that your values are empty strings and would know to go chase after the $_POST to see why it's arriving empty.
Please help!
I'm a complete php/sql newb, and i'm feeling pretty (ok, really) dumb.
I really need help pre-populating text fields of a form i've built for our office staff to contact the workmen in the field, (and the form works well enough); I've searched a million threads, but just could not figure it out...
Only some of the form fields need to pre-populate after a users login, but I have no idea how to make that happen... I've created a mysql DB with a table called 'users', and i know how to open the DB (and close it), but can't figure out how to pull the data from a given row, and populate the fields I need correctly. here's where I'm at:
mysql_connect("localhost", "XXXXX", "XXXXX") or die("Error connecting to MySQL: ".mysql_error());
mysql_select_db("vendor_sqldb") or die("Error selecting database: ".mysql_error());
$sql = mysql_query("SELECT * FROM USERS") or die("Error connecting to table: ".mysql_error());
$rowdetail=mysql_fetch_array($sql);
date_default_timezone_set('America/Los_Angeles');
//1. Add your email address here.
//You can add more than one receipient-
$formproc->AddRecipient('foreman#mysite.com'); //<<--- supervisor email address here
$formproc->SetConditionalField('select field emplyee');
$formproc->AddConditionalReceipent(employee1,'email#email.com');
$formproc->AddConditionalReceipent('employee2','email#email.com');
$formproc->AddConditionalReceipent('employee3','email#email.com');
$formproc->AddConditionalReceipent('employee4','email#email.com');
$formproc->AddConditionalReceipent('employee5','email#email.com');
$formproc->AddConditionalReceipent('employee6','email#email.com');
$formproc->AddConditionalReceipent('employee7','email#email.com');
$formproc->AddFileUploadField('newupload','',1024);//<<------- New file upload
if(isset($_POST['submitted']))
{
if($formproc->ProcessForm())
{
$formproc->RedirectToURL("thank-you.php");
}
And heres the area where I need the help to prepopulate fields:
<p align="center">
<label for='email' ></label>
<label for='name' >Office Staff Employee Name* </label>
<input type='text' name='name' id='name' readonly='readonly' 'value='<?php echo $formproc->SafeDisplay('name') ?>' maxlength="50" value="<?php echo $session->name?>" name="name" />" />
</p>
<p align="center">
<label for='email2' >Your Email Address*</label>
<input type='text' name='email2' id='email2' value='<?php echo $row_Recordset1['email']; ?><?php echo $formproc->SafeDisplay('email') ?>' maxlength="50" />
I'm not sure how to prepopulate the values for office staffer's name, their email etc? I supposed that it was a simple echo command, but if it is, I guess I'm not getting the syntax right?
I'm sure im missing a line of code, which would specify row and collumn containing the data too, but don't know how to write this!?
Thanks a bunch for your help!
Your sql selects a row for each user.
$sql = mysql_query("SELECT * FROM USERS") or die("Error connecting to table: ".mysql_error());
You need to specify which user you are trying to get from the database table. I am going to give you an example for the SQL query if the user's names were stored in a column named "USERNAME":
$sql = mysql_query("SELECT * FROM USERS WHERE USERNAME='name'") or die("Error connecting to table: ".mysql_error());
You can then pull the user specific data and insert it where needed.
I am making a php page that retrieves data from a database table and putting it in a table for the user to see via MySQLi commands.
I was wondering how I should approach the reverse situation. I want the user to be able to enter in information into textboxes and the click a button at the bottom of the page called 'save' which will prompt the user "are you sure" before saving to the database. If the user clicks 'yes', then the new entry is inserted into the database.
I have the following code to create the labels and textboxes:
<FORM>
ID: <input type="text" name="id"><br />
NM: <input type="text" name="nm"><br />
Company: <input type="text" name="company"><br />
Address: <input type="text" name="address"><br />
City: <input type="text" name="city"><br />
Zip: <input type="text" name="zip"><br />
State: <input type="text" name="state"><br />
Phone: <input type="text" name="phone"><br />
Website: <input type="text" name="web_site"><br />
</FORM>
However, when it comes to the 'save' button, I can implement the button just fine, but how would I go about saving the information entered into the database?
My initial thought process was to find the values that the user entered. I'm new to PHP and WEB dev in general, but I need to know how to get the value of the text in the textbox. Would I have to sift all the values through via the PHP Post method?
Once I have the information the user wants to enter, I was thinking maybe MySQLi has an insert function, which I found here, http://php.net/manual/en/mysqli.insert-id.php. Then it's just a quick insert and it's in the database after the user gives the 'yes' at the prompt.
Do I have the right idea in mind? Is there a more efficient way to do this?
Any help is greatly appreciated. I've looked around for problems and solutions similar to the ones related to my scenario but there were none. =(
Thanks!
EDIT:
Here is the code I have on the agentprocess.php that the action form sends the information to:
<?php
$agent_nm = $_POST['nm']; // gather all the variables
$company = $_POST['company'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$state = $_POST['state'];
$phone = $_POST['phone'];
$web_site = $_POST['web_site'];
$batch_id = $_POST['batch_id']; // added batch id
//connect
$conn = new mysqli('local', 'admin', 'pass', 'DB');
if(mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
//generate the query (doesn't add id because id is autoincremented)
$query = "INSERT INTO t_agent VALUES (NULL, " . $agent_nm . ", " . $company . ", " . $address . ", " . $city . ", " . $zip . ", " . $state . ", " . $phone . ", " . $web_site . ", " . $batch_id . ")";
//insert and close.
mysqli_query($conn, $query);
mysqli_close($conn);
Despite the code here, I've queried the table and the new entry is not there. Am I missing something here?
Thanks in advance!
Very simple example, added the label tag to the labels for your input and put it inside of a form.
<form method="post" action="process.php" id="myForm" name="myForm" >
<label for="ID">ID</label>: <input type="text" name="ID" /><br />
<label for="nm">NM:</label> <input type="text" name="nm"><br />
<label for="company">Company:</label> <input type="text" name="company"><br />
<label for="address">Address:</label> <input type="text" name="address"><br />
<label for="city">City</label>: <input type="text" name="city"><br />
<label for="zip">Zip</label>: <input type="text" name="zip"><br />
<label for="state">State</label>: <input type="text" name="state"><br />
<label for="phone">Phone</label>: <input type="text" name="phone"><br />
<label for="web_site">Website</label>: <input type="text" name="web_site"><br />
<input type="submit" name="submit" />// this is your submit button
</form>
On the process.php page
//get your inputs from the form
$ID = $_POST['ID'];
//do the same for each of the text inputs
Then you can use mysqli as you described to insert the values into your database, feel free to comment if you need any help with the mysqli part of the question, I didn't include it here since you had the link posted in the original question.
you need to use forms. yes, using the name attributes in your elements, you sift through $_POST(eg. $_POST['company']) for the values you want to store into the DB. here's an example. Use MYSQLi statements instead of mysql as in the eg.
this is simple yet a little complex task for web development beginers.
So I am going to give you an full example of what you need to do...
To do the SAVE button check the fastest way is to use javascript confirm dialog and if confirmed to submit form with javascript also.
The Mysql insert part is easy, you need to check if there is data that you submited via form in $_REQUSET (this works better than $_POST or $_GET because it catchs it both.) and then to connect to db and do an insert query...
Everything is explained in this example:
http://pastebin.com/thNmsXvn
But please use some template engine like Smarty because doing php, javascript and html in one file without template is awful and long term will give you only problems.
I think that I was very clear in the example I put on pastebin but if you have some questions feel free to ask...
Just to add, I have removed ID from HTML form because the best solution for managing ID's in MySQL is auto increment option, you configure that when you create table and set it to a specific field. Most usually it is ID, and it must be an integer.
You should use PDO functions for PHP/MySQL
id field should be autoincrement
<?php
$host= "xxx";
$username="xxx";
$password="xxx";
$database="xxx ";
// Gets data from URL parameters
$name = $_POST['nm'];
//Repeate for all other parameters
// Opens a connection to a MySQL server
try {
// DBH means "DB Handle"
// MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password);
}
catch(PDOException $e) {
echo $e->getMessage();
}
// STH means "Statement Handle"
$STH = $DBH->prepare("INSERT INTO mytable ( id, nm,company,address,city,zip,state,phone,web_site ) values ( NULL,:nm,:company,:address,:city,:zip,:state,:phone,:web_site)");
$STH->bindParam(':name', $name);
//Repeate for all other parameters
$STH->execute();
//# close the connection
$DBH = null;
?>