inserting fields to MySql table using PHP - php

I am trying to generate a script to insert comments on a blog to 'comments' table in MySsl database
<form action="insertcomment.php" method="post">
<p class ="ctitle">Leave a Comment:</p>
<p>
<label for="name"><b>PostID:</b></label>
<input type="text" id="postid" name="name" maxlength="4" /> <br/>
<label for="name"><b>Name:</b></label>
<input type="text" id="name" name="name" maxlength="25" /> <br/>
<label for="email"><b>Email:</b></label>
<input type="text" id="email" name="email" maxlength="50" /> <br/>
<label for="website"><b>Website:</b></label>
<input type="text" id="website" name="website" maxlength="25" /> <br/>
<label for="content"><b>Comment:</b></label>
<textarea id="content" name="content" cols="10" rows="4" maxlength="800"></textarea> <br/>
<input type="submit" value="Submit Comment" name="submit_comment" /> <br/>
</p>
</form>
and my PHP script is as follows:
<?php
include("dbconnect.php");
$con=new dbconnect();
$con->connect();
error_reporting(E_ALL);
if(isset($_POST['submit'])) {
$sSql = "INSERT INTO comments
( post_id,name, email, website,content)
VALUES ('$_POST[postid]','$_POST[name]', '$_POST[email]', '$_POST[website]', '$_POST[content]')";
mysql_query($sSql);
echo '<h2> Your Comment is submitted</h2><br />';
}
?>
But I was not able to insert my comment into database. my 'comments' table has comment_id,post_id,name,email,website,content,date_published fields. comment_id is the primary key. It has the option auto_increment. and date_published by default gives current time stamp. I was not able to figure out what my error is. Any thoughts would be appreciated.
Thank You!

You should use mysqli or PDO, but if you need to use the about-to-be depreciated mysql plugin:
<?php
include("dbconnect.php");
$con=new dbconnect();
$con->connect();
error_reporting(E_ALL);
if(isset($_POST['submit'])) {
foreach ($_POST as $key => $value) {
$$key = mysql_real_escape_string($value); // You should always sanitize user inputs.
}
$sSql = "INSERT INTO comments
( post_id,name, email, website,content)
VALUES ($postid,'$name', '$email', '$website', '$content')"; // No quotes around $postid because I'm assuming post_id column is an int type.
mysql_query($sSql);
echo '<h2> Your Comment is submitted</h2><br />';
}
?>
Notice the single quotes have been removed from $postid. This is because if table post_id is an int type, then you should not have quotes around the integer value.
Also, notice I've used the mysql_real_escape_string() function to clean your inputs. You should never ever quote direct user-inputted variables into SQL. It's very dangerous as users can use SQL injection attacks to gain access to your DB where they shouldn't or even possibly drop tables.
Still, I recommend converting to mysqli or PDO if at all possible, because the mysql plugin is about to be depreciated.

Related

html form, PHP insert data into database not working?

I have HTML registration form when I submit the form the PHP code appears and data not insert to database i made my database using phpMyAdmin, what should I do?
Here my PHP code:
<?php
$con=mysqli_connect('localhost','root','');
$db=mysqli_select_db($con,'research_sys');
if ($con) {
echo "good";
}else {
die('error');
}
if(isset($_POST['submit'])){
$Fname = mysqli_real_escape_string($con,$_POST["Fname"]);
$Lname = mysqli_real_escape_string($con,$_POST["Lname"]);
$email = mysqli_real_escape_string($con,$_POST['email']);
$password = mysqli_real_escape_string($con,$_POST['password']);
$sql = mysqli_query($con,"INSERT INTO `research_sys`.`researcher` (Re_fname,Re_lname,Re_mobile,Re_password) values ('$Fname','$Lname','$email','$password ')");
if (mysqli_query($sql)){
echo "insert";
} else {
echo "error" .$sql ."<br>". mysqli_error($con);
}
}
?>
here my registration HTML code
<form method="post" action="connect.php">
<legend class="center">Register </legend>
<br>
<div>
<input type="text" name="Fname" placeholder="First Name"/>
</div>
<div>
<input type="text" name="Lname" placeholder="Last Name"/>
</div>
<div>
<input type="text" name="email" placeholder="Email"/>
</div>
<div>
<input type="password" name="password" placeholder="Password"/>
</div>
<div>
<input type="password" name="con_password" placeholder="Password confirm"/>
</div>
<input type="submit" name="submit" value="submit"/>
</form>
Look at the following:
$sql = mysqli_query($con,"INSERT INTO `research_sys`.`researcher`
^^^^^^^^^^^^ function
(Re_fname,Re_lname,Re_mobile,Re_password)
values ('$Fname','$Lname','$email','$password ')");
^ space
if (mysqli_query($sql)){
^^^^^^^^^^^^ function
You're using that mysqli_query() function twice, remove one and just do:
if ($sql){...}
and mysqli_error($con) should have thrown you an error about it.
If it didn't throw an error, then that may suggest you're using this as file:/// as opposed to http://localhost.
Edit:
"i have html registration form whin i submit the form the php code apears"
That's because of what I wrote above before quoting you. You need to run this off a webserver with php/mysql installed and running properly and as http://localhost.
Also, remove the space in this '$password '. That space counts as a character.
Double-check your column names also. There seems to be something that doesn't match (Re_fname,Re_lname,Re_mobile,Re_password) the Re_mobile and you're referencing an email '$email' in VALUES.
You also seem to store plain text passwords; don't, it's not safe if you intend on going live with this. Use password_hash() and a prepared statement.
Footnotes:
$con=mysqli_connect('localhost','root','');
$db=mysqli_select_db($con,'research_sys');
You can shorten that to using all 4 arguments in mysqli_connect():
$con=mysqli_connect('localhost','root', '', 'research_sys');

Updating a Row in PostgreSQL with PHP

I was wondering what the syntax was in PHP to update a row in a PostgreSQL database. I have made a login page that checks a UserName and Password from a database, then it goes to a page where it displays all the user info from the database for that user name. I am trying to allow the user to change some of the columns, like password, name, etc. So I added another page that has fields for each of the columns I want to change.
This is the code I have for the query:
if(array_key_exists('save',$_POST))
{
$firstname=$_POST['ifirstname'];
$lastname=$_POST['ilastname'];
$email=$_POST['iemail'];
$password=$_POST['ipassword'];
$conn_string='host=#### port=#### dbname=###### user=####### password=######';
$dbconn=pg_connect($conn_string) or die('Connection failed');
$query="UPDATE project.customer SET FirstName='$firstname',
LastName='$lastname',Email='$email',Password='$password')
WHERE UserName=$1";
$result=pg_query($dbconn,$query);
$row_count= pg_num_rows($result);
pg_free_result($result);
pg_close($dbconn);
}
This is for the fields:
<div id="header">UPDATE USER INFO</div>
<form id="testform" name="testform" method="post" action="" >
<p> <label for="ifirstname">First Name:</label>
<input name="ifirstname" type="text" id="ifirstname"/>
</p>
<p> <label for="ilastname">Last Name:</label>
<input name="ilastname" type="text" id="ilastname"/>
</p>
<p> <label for="iemail">E-Mail:</label>
<input name="iemail" type="text" id="iemail"/>
</p>
<p>
<label for="ipassword">Password:</label>
<input name="ipassword" type="password" id="ipassword"/>
</p>
<p>
<label for="iconfpass">Confirm Password:</label>
<input name="iconfpass" type="password" id="iconfpass"/>
</p>
<p>
<input type="submit" name="save" value="Register"/>
</p>
</form>
I think it must be like this. Also make user to write old password when changing data for security reason. Also dont forget to filter your data before using in query to avoid sql injection attacks
$query="UPDATE project.customer
SET (FirstName,LastName,Email,Password) =
('$firstname','$lastname','$email','$password')
WHERE UserName= '$1' and Password = '$oldpassword'";
Why not just use standard SQL syntax?
Update project.customer Set
"FirstName" = '$firstname',
...
Where ...
The main difference in Postgres is that you usually quote the column names.

php mysql INSERT INTO mysql by using register form

I am php beginner and I am trying to make e-commerce by using php.
I am trying to make register form and I want to save these data into mysql server.
The coding looks like OK, but the data did not store in mysql server.
Could you give your answer for this? php language is first time that it is what I am struggled. Please give some advice. Thanks.
--registerForm.php--
<h4>Create a new account</h4>
<div class="box">
<form action="register.php" method="post">
<p>User ID: <input type="text" name="userId" size="30"/>*</p>
<p>Password: <input type="password" name="password" size="30"/>*</p>
<p>Retype Password: <input type="password" name="repassword" size="30"/>*</p>
<p>First Name: <input type="text" name="firstName" size="30"/>*</p>
<p>Last Name: <input type="text" name="lastName" size="30"/>*</p>
<p>Your Address (*):</p>
<p> <textarea name="address" rows="5" cols="30"></textarea></p>
<p>Phone: <input type="text" name="phone" size="20"/>*</p>
<p>E-mail: <input type="text" name="email" size="21"/>*</p>
<p><input type="submit" value="Create Account"/></p>
</form>
</div>
--register.php--
<?php
require "sql_connection.php";
if(isset($_POST['submit']))
{
if($_GET["userId"]==$_GET["repassword"]){
mysql_query("insert into customer (userId, password, firstName, lastName, address,
phone, email)
values
('$_GET[userId]','$_GET[password]','$_GET[firstName]','$_GET[lastName]','$_GET[address]','$_GET[phone]','$_GET[email]')")
or die(mysql_error());
}
echo "Done!!!!";
}
?>
--sql_connection.php--
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "**MY_PASS**";
$db_name = "**MY_DB**";
#mysql_connect("$db_host", "$db_username", "$db_pass", "$db_name") or die("connection is fail.");
#mysql_select_db("$db_name") or die("database does not exsist.");
echo "Successfully connection!!";
?>
if($_GET["userId"]==$_GET["repassword"])
Why do you compare userid to a retype pssword field?
I think it should be :
if($_GET["password"]==$_GET["repassword"])
Also make sure you escape strings to prevent SQL Injection Attacks.
http://php.net/manual/en/function.mysql-real-escape-string.php
And Like Paul said, to correctly retrieve the data use $_POST
Few things. Your $_GET and $_POST are mixed up. and NEVER post your db_pass and uername in public. Also, you're suppressing errors using #. don't do that.
i.e.
if($_GET["userId"]==$_GET["repassword"]){
should be
if($_POST["userId"]==$_POST["repassword"]){
and changes all these to $_POST
Your code:
$_GET[userId]','$_GET[password]','$_GET[firstName]','$_GET[lastName]','$_GET[address]','$_GET[phone]','$_GET[email]')
Should be:
$_POST[userId]','$_POST[password]','$_POST[firstName]','$_POST[lastName]','$_POST[address]','$_POST[phone]','$_POST[email]')"
As your form method defined is POST so use $_POST to get values after submit instead of $_GET
require "sql_connection.php";
if(isset($_POST['submit']))
{
if($_POST["userId"]==$_POST["repassword"]){
mysql_query("insert into customer (userId, password, firstName, lastName, address,
phone, email)
values
('$_POST[userId]','$_POST[password]','$_POST[firstName]','$_POST[lastName]','$_POST[address]','$_POST[phone]','$_POST[email]')")
or die(mysql_error());
}
echo "Done!!!!";
}
?>
Values are not quoted properly. You should quote then before insert.
mysql_query("insert into customer (userId, password, firstName, lastName, address,
phone, email)
values
('".$_POST[userId]."','".$_POST[password]."','".$_POST[firstName]."','".$_POST[lastName]."','".$_POST[address]."','".$_POST[phone]."','".$_POST[email]."')")
I think that what you are trying to do is:
if($_GET["password"]==$_GET["repassword"]) {

MySQL Not Inserting Into Column

I have the code below:
<html><body>
<?php
$con = mysql_connect("localhost","will","blahblah");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("blahblah", $con);
$sql="INSERT INTO links (link, notes, username)
VALUES
('$_POST[link]','$_POST[notes]','$_POST[username]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 link added";
mysql_close($con)
?>
</body></html>
It should insert a link and notes and a username into my database but it doesn't. I am clueless as to why and would appreciate some help with it! It is getting these values from the form below:
<div id="stylized" class="myform">
<form id="form" name="form" method="post" action="user.php">
<label>Username
<span class="small">Enter Your Username</span>
</label>
<input type="text" name="name" id="username" />
<label>Link
<span class="small">Paste Your Link</span>
</label>
<input type="text" name="email" id="link" />
<label>Notes
<span class="small">Add Some Notes</span>
</label>
<input type="text" name="password" id="notes" />
<button type="submit"></button>
<div class="spacer"></div>
</form>
</div>
Thanks!
I see at least three problems, with your code :
First, when injecting strings into an SQL query, you must escape it, using mysql_real_escape_string() :
$link = mysql_real_escape_string($_POST['link']);
$notes = mysql_real_escape_string($_POST['notes']);
$username = mysql_real_escape_string($_POST['username']);
$sql="INSERT INTO links (link, notes, username)
VALUES ('$link','$notes','$username')";
Third, in your PHP code, you must use the name attribute of your input fields -- and not their id attributes.
Considering your HTML code looks like this :
<input type="text" name="name" id="username" />
<input type="text" name="email" id="link" />
<input type="text" name="password" id="notes" />
You should work with :
$_POST['name'], and not $_POST['username']
$_POST['email'], and not $_POST['link']
$_POST['password'], and not $_POST['notes']
Note : using a name and an id that are that different leads to troubles ;-)
So, to summarize, your code should look a bit more like this :
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$name = mysql_real_escape_string($_POST['name']);
$sql="INSERT INTO links (link, notes, username)
VALUES ('$email','$password','$name')";
Note : you should use the same names for the input fields, and the fields in the table -- it would make your code easier to understand.
Replace it :
$sql="INSERT INTO links (link, notes, username)
VALUES
('$_POST[link]','$_POST[notes]','$_POST[username]')";
with:
$sql="INSERT INTO links (link, notes, username)
VALUES
('". mysql_escape_string($_POST['name']) ."','".
mysql_escape_string($_POST['email']) ."','".
mysql_escape_string($_POST['password']) ."')";
Note that POST variables you're trying to use in Your query are completely different from those on your form
The indexes of POST variables must match the names of the form items.
So either write:
<input type="text" name="link" id="link" /> or use $_POST[email]
Adapt for the other variables.
id attributes are meaningless when submitting the form. You probably want to swap the name and id attributes.
Currently, $_POST['name'], $_POST['email'] and $_POST['password'] are being submitted instead of $_POST['username'], $_POST['link'] and $_POST['notes'].
Your code is also vulnerable to SQL injection.
The items in $_POST are indexed by name attribute, not by id.

Problem with PHP; Posting Hidden Value?

I have a page which basically allows an admin user to create manager user types (basically a register function. So when the values are submitted, they are stored into the DB, very very basic stuff. However, I have a hidden variable type..reasons are I have 3 different user levels and I have declared they identification as an integer (e.g. 7 = manager, 8 =user etc.)
Can someone help me out with how to correctly pass this hidden value so it stores in the database...
Here is my form:
<form id="userreg" name="userreg" method="post" action="adduser-process.php">
<label>Full Name:</label> <input name="fullname" size="40" id="fullname" value="<?php if (isset($_POST['fullname'])); ?>"/>
<br />
<label>Username:</label> <input name="username" size="40" id="username" value="<?php if (isset($_POST['username'])); ?>"/> <br />
<label>Password:</label> <input name="password" size="40" id="password" value="<?php if (isset($_POST['password'])); ?>"/> <br />
<label>Email Address:</label> <input name="emailaddress" size="40" id="emailaddress" value="<?php if (isset($_POST['emailaddress'])); ?>"/>
<br />
<input name="userlevel" type="hidden" size="1" id="userlevel" value="<?php $_POST[5]; ?>" /> <br />
<input value="Add User" class="addbtn" type="submit" />
</form></div>
Next, here is the script that runs the query:
<?php
require_once "config.php";
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$password = $_POST['password'];
$emailaddress = $_POST['emailaddress'];
$userlevel = $_POST[5];
$sql = "INSERT INTO users_tb VALUES('".$user_id."','".$fullname."','".$username."',MD5('".$password."'),'".$emailaddress."','".$userlevel."')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
header("Location: administratorfrontview.php");
exit();
?>
I'm basically trying to pass the hidden typem with a constant value of '5' just for this form, as it will not be changed...also while im here, for some reason, the 'fullname' is not stored in the DB either!!?? WTH?? all other fields are processed fine. Any help is much appreciated! Thank you.
Two things. One, $userlevel should equal $_POST['userlevel'] not 5 as POST data isn't always in that order. Two, your insert statement should be preceded with the column names (to prevent any data from going in the wrong order).
$sql = "INSERT INFO users_tb (id, name, username, password, email, userlevel) ".
"('".$user_id."','".$fullname."','".$username."',MD5('".$password."'),'".
$emailaddress."','".$userlevel."')";
Your PHP for outputting the value is wrong. Use:
<?= $_POST[5]; ?>
or
<?php echo $_POST[5]; ?>

Categories