MySQL form on MAMP not working properly - php

The problem is I simply want to insert the fullname/address. I created a users table with the following columns: id (primary), fullname (unique), address (unique).
Here's the code:
<?php $username = "root";
$password = "artislife23";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("test",$dbhandle)
or die("Could not select examples");?>
<body>
<div class="container">
<div class="content">
<h1><?php if(($selected!=null)){
echo "Database is on lock.";}
if(($dbhandle!=null)){
echo "Connected to MySQL<br>";
}?></h1>
<form method="post" action="input.php">
<tr><td>Name</td><td><input type="text" name="fullname" size="20"></td></tr>
<tr><td>Address</td><td><input type="text" name="address" size="40"></td></tr>
<tr><td></td><td align="right"><input type="submit" value="Submit"></td>
Here's input.php
<?php
$postr="INSERT INTO users
(fullname, address) VALUES('$_POST[fullname]','$_POST[address]')";
$result = mysql_query($postr);
echo "$result";?>
All that I can see that's happening is a single blank entry was inserted into the table. Am I doing something wrong here? All I want is to successfully insert the form data into my users table here.

$_POST['fullname']
you are missing quotes in your POSTs.

The reason why it doesn't work is that PHP doesn't expand arrays in strings the same way it does variables without some weird syntax I can never remember. Change:
$postr="INSERT INTO users (fullname, address) VALUES('$_POST[fullname]','$_POST[address]')";
To:
$postr="INSERT INTO users (fullname, address) VALUES('".$_POST['fullname']."','".$_POST['address']."')";
You were also missing the quotes on the array keys.
Additional notes:
Your code is wide open to SQL injection, if I entered my name as Bobby'; DROP TABLE users;-- guess what would happen?
mysql_*() functions are deprecated, take the time to learn PDO or MySQLi. They have neat thigns called 'parameterized queries' that allow you to easily avoid SQL injection like I've noted above.
Assuming that either a person's full name or address to be unique to them is a design mistake, don't do this in a 'real-world' project.
Edit
Alternate syntax for embedding arrays in strings:
$string = "Fee fie {$foo['bar']}.";

Related

PHP code for a HTML form sending data to a MySQL database?

I have this form:
<form action="contactus.php" method="post">
<select name="formTitle">
<option value="">Select...</option>
<option value="M">Mr</option>
<option value="F">Mrs</option>
</select>
<p><b>Name</b></p>
<input type="text" name="formName" maxlength="50"/>
<p><b>Enquiry</b></p>
<input type="text" name="formEnquiry" maxlength="500"/>
</select>
<p><input type="submit" name="formSubmit" value="Submit"/></p>
And I have a MySQL database (called 'contacts') with a table (called 'enquiries') with three columns; 'Title', 'Name', 'Enquiry'.
The database has no password or anything. It's just a localhost with a 'root' password.
What kind of PHP would I need to send the data from this HTML form to the MySQL database?
I can help you in this problem.
So, just add the following code to your php file contactus.php.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "contacts";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['formSubmit'])) {
$formTitle = $_POST['formTitle'];
$formName = $_POST['formName'];
$formEnquiry = $_POST['formEnquiry'];
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES ('$formTitle', '$formName', '$formEnquiry')";
$conn->query($sql);
?>
I hope this will solve your problem.
SIMPLE ANSWER: MySQL
A LITTLE BIT MORE DEVELOPED ANSWER:
MySQL is in basic terms the combination of PHP and SQL to create an easy way to do various actions to a database, which include:
Create table
Query table
Update table
and much more
There are variations of MySQL, including MySQLi and MySQL (PDO).
an example of connecting to your database via MySQL (PDO) would be:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$myDB = "databasename";
try {
$conn = new PDO("mysql:host=$servername;dbname=$myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
//insert code there that you want to execute...
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
you mentioned that you don't have a password, so you might just leave the "password" slot empty ("") I suppose, though this is very insecure and I recommend you place a password.
In the code above, there is a comment that says:
//insert code there that you want to execute...
Here you would include code that would probably do actions similar to the ones mentioned above (query table, update table, etc). An example of code similar to that would be:
//htmlspecialchars takes out special characters that might
//exist in the posted information if someone were trying
//to hack your site via sql injection
$formTitle = htmlspecialchars($_POST['formTitle']);
$formName = htmlspecialchars($_POST['formName']);
$formEnquiry = htmlspecialchars($_POST['formEnquiry']);
$sql = "INSERT INTO enquiries (Title, Name, Enquiry) VALUES (formTitleBinded, formNameBinded, formEnquiryBinded)";
$sqlPrepared = $conn->prepare($sql);
$sqlPrepared->bindParam(':formTitleBinded',$formTitle);
$sqlPrepared->bindParam(':formNameBinded',$formName);
$sqlPrepared->bindParam('formEnquiryBinded',$formEnquiry);
$sqlPrepared->execute();
The previous code both sanitizes your input and inserts a row into your table with that information.
Let me know if that helped!
EDITED: My answer has been edited with parameter binding included to prevent SQL Injection.

can't insert data in a mysql database using php

first of all i am pretty new with mysql and php and for now i just want to insert some data in a mysql database form two text box using php.
here the database name is "info" and table name is "students" having three columns like id(primary key, auto increment activated), name and dept. There are two text boxes txtName and txtDept. I want that when i press the enter button the data form the text boxes will be inserted into the mysql database. I have tried the following code but data is not being inserted in the table....
<html>
<form mehtod="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info");
if($_POST){
$name = $_POST['txtName'];
$dept = $_POST['txtDept'];
echo $name;
mysqli_query($con,"INSERT INTO students(name,dept) VALUES($name,$dept);");
}
?>
There are a few things wrong with your posted code.
mehtod="post" it should be method="post" - typo.
Plus, quote your VALUES
VALUES('$name','$dept')
DO use prepared statements, or PDO with prepared statements.
because your present code is open to SQL injection
and add error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
You should also check for DB errors.
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
as well as or die(mysqli_error($con)) to mysqli_query()
Sidenote/suggestion:
If your entire code is inside the same file (which appears to be), consider wrapping your PHP/SQL inside a conditional statement using the submit button named attribute, otherwise, you may get an Undefined index... warning.
Naming your submit button <input type="submit" name="submit" value="Enter"/>
and doing
if(isset($_POST['submit'])){ code to execute }
Just doing if($_POST){ may give unexpected results when error reporting is set.
Rewrite: with some added security using mysqli_real_escape_string() and stripslashes()
<html>
<form method="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" name="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
if(isset($_POST['submit'])){
$name = stripslashes($_POST['txtName']);
$name = mysqli_real_escape_string($con,$_POST['txtName']);
$dept = stripslashes($_POST['txtDept']);
$dept = mysqli_real_escape_string($con,$_POST['txtDept']);
echo $name;
mysqli_query($con,"INSERT INTO `students` (`name`, `dept`) VALUES ('$name','$dept')")
or die(mysqli_error($con));
}
?>
As per the manual: http://php.net/manual/en/mysqli.connect-error.php and if you wish to use the following method where a comment has been given to that effect:
<?php
$link = #mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
?>
God save us all...
Use PDO class instead :). By using PDO you can additionally make prepared statement on client side and use named parameters. More over if you ever have to change your database driver PDO support around 12 different drivers (eighteen different databases!) where MySQLi supports only one driver (MySQL). :(
In term of performance MySQLi is around 2,5% faster however this is not a big difference at all. My choice is PDO anyway :).

mysql UPDATE not changing table

I have a made a form to allow for changing a users "UserLevel." However, I cannot seem to get it to work. It just is not changing the UserLevel after submit. I am definitely a PHP newbie. But I have tried researching this for the past hour and cannot seem to make any progress here. Probably something simple I am missing. Any help is appreciated.
The form
<form action="dm/userUpdate.php" method="post">
Username: <input type="text" name="username" value="Username">
<br>
User Level: <input type="number" name="userlevel" value="0">
<input type="Submit" name="submit" value="Change">
</form>
userUpdate.php
<?php
mysql_connect('localhost', 'username', 'password') or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$userlevel = mysql_real_escape_string($_POST["userlevel"]);
$username = mysql_real_escape_string($_POST["username"]);
mysql_query($con,"UPDATE users SET UserLevel= $userlevel WHERE Username ='$username'");
mysql_close($con);
?>
You should escape your variables. Or whatever this is called.
mysql_query("UPDATE users SET UserLevel= '".$userlevel."' WHERE Username ='".$username."'");
Notice i used regular MySQL so no link is required as a parameter. If you are new to MySQL i advice to learn MySQLi right off the bat since it has some handy improvements.
You can't mix mysqli (note the I) and mysql (without an i) functions. The two libraries are NOT interchangeable.
As well, your SQL itself has syntax errors - mysql_real_escape_string() does NOT quote strings for you - it only escapes sql metacharacters, so you'll end up something like
... WHERE Username = Miles O\'Brien
instead of
... WHERE Username = 'Miles O\'Brien'
try this
mysql_query("UPDATE users SET UserLevel= '$userlevel' WHERE Username ='$username'");
mysql_close();
you have no $con variable defined.
Always check for syntax errors. Look at your table name and table fields and make sure they are spelled the same as well as cased.
<?php
$con = mysql_connect('localhost', 'username', 'password') or die(mysql_error());
mysql_select_db("database", $con) or die(mysql_error());
$userlevel = mysql_real_escape_string($_POST["userlevel"], $con);
$username = mysql_real_escape_string($_POST["username"], $con);
mysql_query("UPDATE users SET UserLevel= " . $userlevel . " WHERE Username ='" . $username . "'", $con);
mysql_close($con);
?>
use $con to hold connection link on connected data base and use mysql_query (not mysqli_query it is for MySQLi) and other functtions with that connection variable to work with connected database!

php code working incorrectly and not querying database

I'm using php and a database to add books to a database.
HTML
<form method="POST" action="addbook.php">
<p>Enter Book title :<input type="text" name="bookname"></p>
<p>Enter Book Author :<input type="text" name="bookauthor"></p>
<p><input type="submit" value="addbook"></p>
</form>
PHP
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbcon = mysqli_connect('localhost','root','password','bookstore') or die('asd');
$dbquery = "INSERT INTO books (title,author) VALUES ($bname,$bauthor)";
mysqli_query($dbcon,$dbquery) or die('not queryed');
echo "Your book has been added to your online library";
I'm getting the reply ' not queryed'
try putting single quotes around the values
ie
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";
You should be using PDO and prepared statements in order to prevent SQL injection. The resultant PHP would be something like this:
$bname = $_POST['bookname'];
$bauthor = $_POST['bookauthor'];
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); //Fill in these variables with the correct values ('localhost' for host, for example)
$st = $dbh->prepare("INSERT INTO books (title,author) VALUES (?,?)");
$data = array($bname, $bauthor);
$st->execute($data);
You can then add logic to check if the statement executed successfully.
Also, I think you just gave us your root password?
For more information about PDO, see this tutorial.
Check the Column names in the table,whether they match with the one in the query.also check whether they are varchar itself.
I dont find any problem in the query, and also try putting
or die(mysqli_error());
and tell what exactly you can see.
If the type is varchar , you have to use single quotes around the values.
$dbquery = "INSERT INTO books (title,author) VALUES ('$bname','$bauthor')";

Trying to add form data into MYSQL database

I currently have an HTML form with various feilds one for example is :
Please Enter First Name: <input type ="text" name="First_Name" /> <br />
I am trying to get the information from this form into my database. But it does not seem input anything into the database. Code is as follows.
<?php
$dbname='ecig';
$dbhost='localhost';
$dbpass='password';
$dbuser='eciguser';
$dbhandle = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("ecig",$dbhandle)
or die("Could not select examples");
$res=mysql_query("INSERT INTO Persons (First_Name, Second_Name) VALUES('$_POST[First_Name]', yes)");
mysql_close();
if (array_key_exists ('check_submit', $_POST ))
echo "Your Name is : {$_POST['First_Name']}<br />";
echo "Your Second Name is : {$_POST['Second_Name']}<br />";
echo "Your Email Address is : {$_POST['Email_Address']}<br />";
echo "Your Password Is : {$_POST['Password']}<br />";
?>
The question is as this is having no impact on my database, is there something i am missing and need to add to my SQL code so that the php and the SQL interact with each other and input the data?
Or am i missing something from the INSERT INTO statement?
Anyway help would be appreciated, Thanks.
There's an error in your query, 'yes' at the end must have quotes.
Try running your query first directly against MySQL to determine if your syntax is correctly, then just replace the values you want.
Should look like this for your example:
$res=mysql_query("INSERT INTO Persons (First_Name, Second_Name) VALUES ('$_POST[First_Name]', 'yes')");
A bit of advice, sanitize your input if you are receiving data from the user, or you will be vulnerable to a SQL injection attack.
And use mysqli_ functions since mysql_ functions are officially deprecated by now. You can read more about those in almost any site, like w3schools.com
Full example of insert with mysqli_ : http://www.w3schools.com/php/php_mysql_insert.asp
Good luck
Use mysql_real_escape_string()
$res=mysql_query("INSERT INTO Persons (First_Name, Second_Name) VALUES ('".mysql_real_escape_string($_POST['First_Name'])."', '".mysql_real_escape_string($_POST[Second_Name])."')");

Categories