Update Mysql column field based on email address - php

My DB has columns: ID, first_name, email, password, level
I have a form that i am trying to update the 'level' column based on the 'email address' entered of the existing user.
Right now i have a basic form that just inserts the info, but i need it to update existing users based on the email value.
This is what i have
<form action="update.php" method="post">
<input type="hidden" name="action" value="update" />
<fieldset>
<label for="email" />Email Address:</label>
<input value="" type="text" name="email" id="email" />
<label for="level" />Level:</label>
<input value="vip" type="text" name="level" id="level" />
<input class="button" type="image" src="/img/right/get-started-button.png" />
</fieldset>
</form>
----update.php------
<?php
$email = $_POST['email'];
$level = $_POST['level'];
mysql_connect ("localhost", "username", "pass") or die ('Error: ' . mysql_error());
mysql_select_db ("db_name");
$query="INSERT INTO users (email, level)VALUES ('".$email."','".$level."')";
mysql_query($query) or die ('Error updating database');
echo "Database Updated With: " .$email. " ".$level ;
?>

Not knowing what version of MySQL your using, you can use INSERT ON DUPLICATE KEY UPDATE syntax if your on 5+: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If your using an older version then a simple select id limit 1 should suffice to find if the record exists.
BTW: you should be using mysql_real_escape_string (or similar) before you execute your sql statement. Its also a good idea to always use back ticks ` around your field names just in case you hit a reserved word or invalid symbol in your field names.

I'm not sure If i uderstand your question correctly, but if you are looking for the sql update:
UPDATE users Set level='some_value' WHERE email="some_email_address"
So you could do:
$query="UPDATE users SET level='" .$level."' WHERE email='" .$email."'";
That is if I understood your question correctly.
As in you are trying to update an existing table, based on the email address typed into the form.

Related

Updating database based on certain ID

I have a table within my database containing subscriptions, each subscription has a name, id and a notes column.
I'm trying to allow the user to update the notes column through a text area on the webpage. All of the subscriptions are in a list on the page which allows the user to click on them to view that specific subscription.
How would I make sure the note that is updated is correct with the id of the subscription they have clicked on?
I currently have this code.
<form method="POST" action="noteAction.php">
<textarea id="notes" name="noteValue">$notes</texarea>
<input type="submit" name="submit"/>
</form>
This is what I think my noteAction.php should look like however I cannot get it working.
mysql_connect ("host", "user", "password") or die ('Error: ' . mysql_error());
mysql_select_db("database_name") or die ('Data error:' . mysql_error());
$text = mysql_real_escape_string($_POST['noteValue']);
$query="UPDATE `subscription` SET `notes`= '$text' WHERE `id` = '$id'";
mysql_query($query) or die ('Error updating database ' . mysql_error());
Any help would be great, thanks.
Use hidden element to store your id inside it.
<form method="POST" action="noteAction.php">
<textarea id="notes" name="noteValue">$notes</texarea>
<input type="hidden" name="id" value="id" value="your id goes here" />
<input type="submit" name="submit"/>
</form>
When you're putting the note in the form, you must have an id for that note kicking about somewhere, after you retrieved it from the database. If you only selected the note contents in that query, select the ID as well. Then pass the ID over in a hidden field, and you have the ID to use in the MySQL query (which is correct).
<input type="hidden" name="note-id" value="note_id_here">

Inserting datafrom form into mysql with POST method

I havent do php for some time, but i dont really see what am I missing.
I am trying to insert some datas from FORM into MYSQL , but it still fail.
This is the file with FORM :
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<title>registrace</title>
</head>
<body>
<H1> The Best Page! </H1>
<p>
"Please registrate"
<form action="zpracovani.php" method="post">
Name <input type="text" size="20" name="Name" value=""><br>
Surname <input type="text" size="30" name="Surname" value=""><br>
Username <input type="text" size="30" name="username" value=""><br>
Password <input type="text" size="10" name="password" value=""><br>
Retype password <input type="text" size="10" name="password2" value=""><br>
<input type="image" name="button" value="submit" class="button" src="button.jpg">
</form>
</p>
</body>
</html>
As you can see i am sending data to proceed into file "zpracovani.php". I did test if i am connected to mysql server ( It passes ) and also a check if i am connected to the right database ( Also passes with no probs ).
<html>
<?php
echo "Wait please";
$con=mysql_connect ('localhost','root','');
if (!$con)
{
die ( 'Could not connect: ' . mysql_error());
}
mysql_select_db ('registrace') or die("cannot select DB");
echo #mysql_ping() ? 'true' : 'false';
$sql="INSERT INTO 'registrace'(Name, surname, username, password).
VALUES('$_POST[Name]','$_POST[Surname]','$_POST[username]','$_POST[password]')";
$result=mysql_query($sql);
if($result){
echo("<br>Input data is succeed");
}else{
echo("<br>Input data is fail");`
}
mysql_close($con);
?>
</html>
Below is overwiev of mysql table I made.
ID int(11)
Name varchar(20) latin1_swedish_ci
Surname varchar(30) latin1_swedish_ci
username varchar(30) latin1_swedish_ci
password varchar(10) latin1_swedish_ci
However I am connected to the database and to correct table it still is unable to insert anyone into the database. Can anyone look into this and help me out, please?
Thanks in advance!
Either remove the quotes in 'registrace' or use backticks in INSERT INTO 'registrace'
Example:
INSERT INTO `registrace`
Using backticks is better.
Also remove the dot in:
$sql="INSERT INTO 'registrace'(Name, surname, username, password).
It should read as:
$sql="INSERT INTO `registrace` (Name, surname, username, password)
Reformatted:
$sql="INSERT INTO `registrace` (Name, surname, username, password)
VALUES
('{$_POST['Name']}','{$_POST['Surname']}','{$_POST['username']}','{$_POST['password']}')";
Or follow this convention:
$unsafe_variable = $_POST["user-input"]
$safe_variable = mysql_real_escape_string($unsafe_variable);
mysql_query("INSERT INTO table (column) VALUES ('" . $safe_variable . "')");
NOTE: I also noticed that you are using the same name for both your DB and your table.
Make sure that this is in fact the case.
Your DB:
mysql_select_db ('registrace')
and your table?
INSERT INTO `registrace`
Plus, it would be a good idea to increase the values for your VARCHAR's and consider using MySQLi_ and prepared statements or PDO. MySQL_ functions are deprecated.
Do read the following articles:
How can I prevent SQL injection in PHP?
On owasp.org
First: use mysqli
Second: get rid of mysql ping
Third: change:
"......'$_POST[xxx]'......"
into:
"......'{$_POST['xxx']}'....."
Thanks guys it is working now.
By the way the mysql ping was just a check to see if i am well connected as i wrote in my original post :)
Anyway it was very helpful thx

PHP FORM INSERT INTO not inserting records

I'm working on a Uni assignment and am having trouble inserting records to MySQL database using a form. My set up is below.
I can view entries in the database with no problem. I'm new to this so sorry in advance :(
conninfo.php
<?php
$strServer="localhost";
$strDatabase="djdatabase"; // CHANGE TO YOUR DATABASE NAME HERE
$strUser="root";
$strPwd=""; // Leave blank for WAMPServer
$strDB=mysql_connect($strServer,$strUser,$strPwd)or die("Could not open database");
$database=mysql_select_db("$strDatabase",$strDB);
?>
addnewdata.php
<?php include "conninfo.php";
$newdj=$_POST["dj"]; //pick up from form
$newfn=$_POST["fn"];
$newem=$_POST["em"];
$newwe=$_POST["we"];
$newpi=$_POST["pi"];
$newev=$_POST["ev"];
$query = "INSERT INTO dj(DJName, FirstName, Email, Website, Picture, EventNumber)VALUES('$newdj', '$newfn', '$newem', '$newwe', '$newpi', '$newev)";
mysql_query($query);
header("location:showall.php");
?>
enternewdata.php
<?php include "conninfo.php";?>
<html>
<head>
</head>
<body>
<form action="addnewdata.php" method="post">
DJ Name:<input type="text" name="dj"><br>
FirstName: <input type="text" name="fn" /><br>
Email: <input type="text" name="em" /><br>
Website: <input type="text" name="we" /><br>
Picture: <input type="text" name="pi" /><br>
EventID: <input type="text" name="ev" /><br>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Many Thanks for your help :)
had better use SET command to insert data
$query = "INSERT INTO dj SET
DJName=".$newdj.",
FirstName=".$newfn.",
Email=".$newem.",
Website=".$newwe.",
Picture=".$newpi.",
EventNumber=".$newev."";
$save = mysql_query($query);
if($save){
header("location:showall.php");
}else{
die(mysql_error());
}
You are missing a quote ' wich is causing the error that you cannot see because you haven't done any debug. Anyway you should just change to this
'$newwe', '$newpi', '$newev')"; //a quote was missing after '$newv
I would suggest you to also debug query by adding or die('INVALID QUERY: ' . mysql_error());
so code would look like
mysql_query($query) or die('INVALID QUERY: ' . mysql_error());
Since you said this is an university test I don't know if you are supposed to use mysql_* function (wich are deprecated), but I would strongly reccommend to switch to mysqli or PDO if you can for security reason.
You missed ' on your query on $newev that gives you an error
$query = "INSERT INTO dj(DJName, FirstName, Email, Website, Picture, EventNumber)VALUES('$newdj', '$newfn', '$newem', '$newwe', '$newpi', '$newev)";

trouble populating form fields from mysql table

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.

Saving to MySQL database via html forms

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

Categories