The code below should write code into the database.
I have divided into two parts HTML AND PHP code are separate. HTML form code is shown below:
<form name="form1" action="insert.php" method="post">
<h3>Ime </h3> <input type="text" name="field1" > <br/> <br/>
<h3>Prezime </h3> <input type="text" name="field2" > <br/> <br/>
<h3>Firma </h3> <input type="text" name="field3" > <br/> <br/>
<h3>Adresa </h3><input type="text" name="field4" > <br/> <br/>
<h3>Telefon </h3> <input type="text" name="field5" > <br/> <br/>
<h3>Fax </h3><input type="text" name="field6" > <br/> <br/>
<h3>Mobitel </h3> <input type="text" name="field7" > <br/> <br/>
<h3>Email </h3> <input type="text" name="field8" > <br/> <br/>
<h3>Web stranica </h3> <input type="text" name="field9" > <br/>
</form>
PhP code is shown below.
$host="localhost"; // Host name
$username="root"; // username
$password="le30mu09"; // password
$database="imenik"; // Database name
$tbl_name="clanovi"; // Table name
// Replace database connect functions depending on database you are using.
$field1=$_POST['field1'];
$field2=$_POST['field2'];
$field3=$_POST['field3'];
$field4=$_POST['field4'];
$field5=$_POST['field5'];
$field6=$_POST['field6'];
$field7=$_POST['field7'];
$field8=$_POST['field8'];
$field9=$_POST['field9'];
$link=mysql_connect("$host", "$username", "$password");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db("$database");
if (!$db_selected) {
die ('db is not selected : ' . mysql_error());
}
$query = "INSERT INTO `clanovi`(`Ime`, `Prezime`, `Firma`, `Adresa`, `Telefon`, `Fax`, `Mobitel`, `Email`, `Web_stranica`) VALUES ( "$field1", "$field2", "$field3", "$field4", "$field5", "$field6", "$field7", "$field8", "$field9")";
mysql_query($query);
mysql_close();
You need to tell us what the actual error is. And bone up on PDO and the dangers of sending unsanitised POST variables to the DB as a matter of priority.
Modify your Insert query. It should be like this:
INSERT INTO clanovi
(column1,column2,column3,...)
VALUES
( $field1, $field2, $field3,.....)
You appear to be using a lot of quotation marks in places that you shouldn't be using them in. It is funny how you can code something for 5 hours and then try to debug it for 2 hours because of a simple quotation mark! It's funny and very depressing at the same time :(
Ok, let's fix the code a little bit!
Database
$link=mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db($database);
if (!$db_selected) {
die ('db is not selected : ' . mysql_error());
}
Notice how I stripped all of the quotation marks out of the code? That will help with database connection and selection.
Now let's move onto the actual inserting of the information into the database!
$query = "INSERT INTO clanovi ('Ime', 'Prezime', 'Firma', 'Adresa', 'Telefon', 'Fax', 'Mobitel, 'Email', 'Web_stranica') VALUES ( $field1, $field2, $field3, $field4, $field5, $field6, $field7, $field8, $field9)";
Again, I stripped all of the quotation marks. Plus I removed backticks and replaced with a ' and also took the '' off of your table name - You should nly use quotation marks when not using a variable.
//Correct
VALUES ($field1, "textnotvariable", $field2...
//Incorrect
VALUES ("$field1", "textnotvariable", "field2"...
The same goes with echo statements. Here's an example...
$myname = "MrJustin";
//Correct
echo $myname;
//or
echo "My name is ". $myname .", it's nice to meet you!";
//Incorrect
echo "My name is $myname, it's nice to meet you";
You'll notice how I used ". $myname ." - that tells the echo to break away from using text, and to pass a variable! :) That to me is the best way to explain how quotations will break a code.
Oh, and you should ALWAYS sanitize your inputs/outputs when using foreign code. I would do some Google searching on that one, and then chat us back up if you run into problems with that!
Hopefully this helps, and happy coding!!
you are not selecting database. you are using double quotes in not its place.
replace this
$db_selected = mysql_select_db("$database");
by
$db_selected = mysql_select_db($database);
and also replace this
$link=mysql_connect("$host", "$username", "$password");
by
$link=mysql_connect($host, $username, $password);
i recomand you to use PDO or mysqli instead.
Related
Im trying to add a new user name to mysql table throw wordpress. But everytime I try to do it, I have no error message, but there are no lines added to the data base.
This is the wordpress page with the php inside:
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("foundint_Sababa", $con);
$sql="INSERT INTO `Users` (`sName`, `sEmail`)
VALUES ('{$_POST['sName']}','{$_POST['sEmail']}')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$info = mysql_info(); echo $info;
mysql_close($con);
?>
I can't see whats wrong. I think it may be something wrong with the connection. Any ideas?
Thank you!
Edit
As suggested, Im trying to use $wpdb so I've created a php file in a folder call my-codes (at the same level of wp-admin, wp-content and wp-includes) and I added the following code to a file call insertUser.php:
<?php
global $wpdb;
$wpdb->insert("wp_submitted_form", array(
"sName" => $sName,
"sEmail" => $sEmail));
?>
Now in my page Im trying to call this function and Im doing this:
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
if(isset($_POST['Submit']))
{
include("./my-codes/insertUsers.php");
}
?>
And im still not being able to insert any row in the database. Any suggestions?
EDIT
I needed a pluggin to actually connect my sql database with wordpress. The code is correct.
Replace your code with the code that i have provided.
<table>
<form name="form1" method="post" action="">
<strong>Please enter your information in order to download the Macs Cabs
App</strong>
<tr><td>
Name:</td><td><input name="Name" type="text" id="sName"></td></tr>
Email Address:</td><td><input name="Email" type="text" id="sEmail"></td> </tr>
<tr><td>
<input type="submit" name="Submit" value="Submit"></td></tr>
</form></table>
<?php
$con = mysql_connect("localhost","root","root"); // ensure that your password in empty or root in your localhost
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("foundint_Sababa", $con);
if(isset($_POST['Submit']))
{
// Previous Insert Query which has discrepency in form input names and Insert Values
//$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('{$_POST['sName']}','{$_POST['sEmail']}')";
// My new Query with corrected form input names for Input Values during POST.
$sql = "INSERT INTO `Users`(`sName`, `sEmail`) VALUES ('".$_POST['Name']."','".$_POST['Email']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
$info = mysql_info(); echo $info;
mysql_close($con);
}
Finally have a check at the table field Names and my code works fine hope it will serve you to.
use the query like this one to make thing happen,
$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('".$_POST['sName']."','".$_POST['sEmail']."')";
for preventing from injection you can use this way to build query.
$name=addslashes($_POST['sName']);
$email=addslashes($_POST['sEmail']);
$sql="INSERT INTO `Users` (`sName`, `sEmail`) VALUES ('$name','$email')";
using prepared statement
$mysqli = new mysqli("example.com", "user", "password", "database");
$name=addslashes($_POST['sName']);
$email=addslashes($_POST['sEmail']);
$stmt=$mysqli->prepare("INSERT INTO `Users` (`sName`, `sEmail`) VALUES (?,?)");
$stmt->bind_param("ss", $name,$email);
$stmt->execute();
for detailed on prepared statement got to http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
So I am very new to PHP,and databases in general, so please be indulgent! :)
I created a simple form in an HTML file:
<h1> Créez votre compte ici</h1>
<form action="form.php" method="post">
<p id="textdone"> </p>
<input type= "text" name="Surname" autocomplete="on" placeholder="Votre nom" required/> <br> <br>
<input type= "text" name="Name" autocomplete="on" placeholder ="Votre prenom" required/> <br> <br>
<input type= "email" name="Email" autocomplete="on" placeholder ="Adresse mail" required/> <br><br>
<input type= "text" name="Pseudo" autocomplete="off" placeholder ="Votre pseudo" maxlength="20" required/> <br>
<p>Ajoutez une photo de profil: <input type= "file" /> <br><br></p>
<p> Entrez un mot de passe: <input type="Password" name="Passwird" autocomplete="off" maxlength="20" required placeholder="Mot de passe"/> <br><br>
Validez votre mot de passe: <input type="password1" autocomplete="off" maxlength="20" required placeholder="Mot de passe"/> <br><br>
</p>
<input type="submit" value="Soumettre"/>
</form>
</body>
And so my action file, the form.php file, saved in the same folder (I made sure) is as follows:
<?php
define('DB_NAME', 'Matchy');
define('DB_USER', 'root#localhost');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link){
die('Could not connect: ' .mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected){
die('Can\'t use' . DB_NAME. ':'. mysql_error());
}
echo 'Successful connection';
$surname = $_POST['Surname'];
$name = $_POST['Name'];
$email = $_POST['Email'];
$pseudo = $_POST['Pseudo'];
$password = $_POST['Password'];
$sql = "INPUT INTO users (Name) VALUES ('$name')";
$sql1 = "INPUT INTO users (Surname) VALUES ('$surname')";
$sql2 = "INPUT INTO users (Pseudo) VALUES ('$pseudo')";
$sql3 = "INPUT INTO users (Email) VALUES ('$email')";
$sql4 = "INPUT INTO users (Password) VALUES ('$password')";
if (!mysql_query($sql)) {
die ('Error: ' .mysql_error());
}
if (!mysql_query($sql1)) {
die ('Error: ' .mysql_error());
}
if (!mysql_query($sql2)) {
die ('Error: ' .mysql_error());
}
if (!mysql_query($sql3)) {
die ('Error: ' .mysql_error());
}
if (!mysql_query($sql4)) {
die ('Error: ' .mysql_error());
}
mysql_close();
?>
But every time I fill out my form and hit submit, I get this message:
Cannot Post /form.php.
I get this code from this following video (https://www.youtube.com/watch?v=wp6Ngpk5XiY&index=2&list=PL530D33D6E548481F), which was very useful. But I really can't connect. I created my table on my database, with all the right columns.
I use phpMyAdmin.
Thank you so much to anyone who can help!! :)
Let's outline the errors here.
INPUT INTO isn't a valid MySQL expression, the syntax is INSERT INTO.
Then you have name="Passwird" and $_POST['Password'] which do not match and error reporting http://php.net/manual/en/function.error-reporting.php would have told you about it.
Then as outlined in comments by another member:
<input type="password1" autocomplete="off" maxlength="20" required placeholder="Mot de passe"/> this one is providing no love too. No inputtype password1 – Hendra Nucleo
which should have been password and not password1.
Best to use the right and official references http://dev.mysql.com/doc/en/insert.html and switch to PDO with prepared statements or mysqli_* with prepared statements, as the mysql_* functions are deprecated. The official manuals are the best references.
They won't steer you wrong ;-)
That tutorial probably didn't mention anything about SQL injection, so that's a good read in its own right.
Nor did it mention anything about passwords.
I noticed that you may be storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
Important sidenote about column length:
If and when you do decide to use password_hash() or the compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/, it is important to note that if your present password column's length is anything lower than 60, it will need to be changed to that (or higher). The manual suggests a length of 255.
You will need to ALTER your column's length and start over with a new hash in order for it to take effect. Otherwise, MySQL will fail silently.
Edit:
That whole block of code could have easily been done in a few lines, such as and without so many calls to the same table:
$sql = mysql_query("
INSERT INTO users (Name, Surname, Pseudo, Email, Password)
VALUES ('$name', '$surname', '$pseudo', '$email', '$password')
");
if($sql){
echo "Success!";
}
else { "Error: " . mysql_error(); }
Yeah, #gmiley raised a good question, check whether you can use input or not and instead use insert query with all the values in single statement. For syntax, you can refer the following link:http://www.w3schools.com/sql/sql_insert.asp
im trying out some code by my own. I just started to learn PHP & mysql. Could anyone tell me where is the mistake? I got a error when processing the query.
My db is set like in the code.
Db name: sweepstakes
Table name: alfa
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "sweepstakes";
$db = mysqli_connect($dbhost,$dbuser,$dbpass, $dbname);
if(mysqli_connect_errno()){
die("Database connection failed: " .
mysqli_connect_errno() .
" (" . mysqli_connect_errno() . ")"
);
}
if($_SERVER['REQUEST_METHOD']=='POST'
&& $_POST['submit']=='Submit'
&& !empty($_POST['name'])
&& !empty($_POST['description'])
&& !empty($_POST['adress'])) {
$name = $_POST['name'];
$desc = $_POST['description'];
$adress = $_POST['adress'];
$query = "INSERT INTO alfa (name, description, adress) VALUES ('$name', '$desc', '$adress')";
$result = mysqli_query($db, $query);
if($result){
}else{
die("Database query failed." . mysql_error() . " " . mysqli_connect_error($db));
}
} else { echo "Empty!";
}
?>
<form method="post" action="index.php">
<fieldset>
<legend>New Sweepstakes</legend>
<label>Name: </br>
<input type="text" name="name" maxlength="150" />
</label> </br>
<label>Description:</br>
<textarea name="description" cols="45" rows="10"></textarea>
</label> </br>
<label>Adress:</br>
<input type="text" name="adress" maxlength="1080" />
</label> </br>
<input type="submit" name="submit" value="Submit" />
</fieldset>
</form>
You're mixing mysql and mysqli functions. Stick with mysqli, mysql is deprecated (don't use it).
In case you didn't spot it: mysql_error() should be mysqli_error()
In addition to checking what Halcyon writes ( using mysqli_error() ), I would also check the query string itself. Just echo out $query right after it's built (the $query = "INSERT..." line) and when running the script look to see if the output matches what you expect to happen, ie that you see something like INSERT INTO alfa (name, description, adress) VALUES ('fred', 'blonde dude', 'Anywhere 32B'). If anything looks out of place (like maybe you have a ' or " in the inputed data and it's screwing up the string output), fix it and try again.
echo and print and print_r()are your friends when doing detective work on new code to see what is the output expected.
(edit)
After reading your update with Halcyon, you should probably check how your auto-incremented field is set up. If, for example, you've been tinkering with this for a while but only set the auto-increment field to INT(2), you might have run out of space for numbers (can only go up to 99 with INT(2)). Increase it to INT(11) or something similar, empty the table, and try again. You can also try ALTER TABLEtable_nameAUTO_INCREMENT = 1 to reset the auto numbering.
I have been successful at posting the answers to some questions. Now i want to take those answers and translate them to some text further explaining their options. Can anyone point me in the right direction? I feel like im stumped, this is my first attempt at php. any help would be amazing.
Here is my first page:
<body>
<div id="container">
<div class="title"><h1>Mortgages</h1></div>
<div class="content">
<form name="myform" action="process.php" method="POST">
<input type="hidden" name="check_submit" value="1" />
Name: <input type="text" name="Name" />
<br /><br />
How soon are you interested in purchasing your new home <br />
<input type="radio" name="timeFrame" value="90_days" /> 90- Days
<input type="radio" name="timeFrame" value="1_Year" /> 1 Year
<input type="radio" name="timeFrame" value="Just_Shopping" /> Just Shopping
<br /><br /><br />
Are you interested in getting more information on any of the following: <Br />
<input type="checkbox" name="Programs[]" value="FHA" checked="checked" /> FHA
<input type="checkbox" name="Programs[]" value="Conventional" /> Conventional
<input type="checkbox" name="Programs[]" value="VA" /> VA
<input type="checkbox" name="Programs[]" value="HELOC" /> HELOC
<br /><br />
<input type="submit" />
</form>
</div>
</div>
</body>
Her is my PHP
<?php
//Check whether the form has been submitted
if (array_key_exists('check_submit', $_POST)) {
//Check whether a $_GET['Languages'] is set
if ( isset($_POST['Programs']) ) {
$_POST['Programs'] = implode(', ', $_POST['Programs']); //Converts an array into a single string
}
echo "Your name: {$_POST['Name']}<br />";
echo "How soon are you interested in purchasing your new home: {$_POST['timeFrame']}<br />";
echo "You interested in getting more information on any of the following: {$_POST['Programs']}<br />";
} else {
echo "You can't see this page without submitting the form.";
}
?>
:--------------------------------------------------------Take two
Okay now I have my data being written to in a database using the following code:
<?php
define('DB_NAME', 'butler_site');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('can\'t use' . DB_NAME . ': ' . mysql_error());
}
$value = $_POST['name'];
$sql = "INSERT INTO mortgage (name) VALUES ('$value')";
if (!mysql_query ($sql)) {
die('Error: ' . mysql_error());
}
$value = $_POST['email'];
$sql = "INSERT INTO mortgage (email) VALUES ('$value')";
if (!mysql_query ($sql)) {
die('Error: ' . mysql_error());
}
$value = $_POST['timeFrame'];
$sql = "INSERT INTO mortgage (timeframe) VALUES ('$value')";
if (!mysql_query ($sql)) {
die('Error: ' . mysql_error());
}
$value = $_POST['programs'];
$sql = "INSERT INTO mortgage (programs) VALUES ('$value')";
if (!mysql_query ($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
?>
What function should I use to take the data and attach it to some data that will explain the program further?
I think you should store this data into the session and navigate to the products page. On the products page you can retrieve this data easily from the session.
Here is how to store data into the session
session_start();
$_SESSION["name"] = $_POST["name"];
$_SESSION["timeFrame"] = $_POST["timeframe"];
$_SESSION["Programs"] = $_POST["Programs"];
Then navigate to the products page :
header('Location: http://www.example.com/');
To retrieve the data on the products page :
$name = $_SESSION["name"]
$timeframe = $_SESSION["timeFrame"]
$Programs = $_SESSION["Programs"]
This way your data will be kept untill the user leaves your site. I would suggest to store the data in a database for more practical example.
For more info about sessions :
http://www.w3schools.com/php/php_sessions.asp
For more info about header function :
http://au1.php.net/manual/en/function.header.php
EDIT: After seeing your updated code. You seem to have a good start in database programming. I advice you to take your time and create a solid base to build on. As of your code I have two notes :
Your SQL queries could all be made in one query like this
INSERT INTO mortgage (name, email, timeframe, programs) VALUES (.....)
You are using old deprecated functions (Meaning: not supported and not advised to be used). This includes all your mysql_* functions. To make the right start you should start using mysqli_* for example the connection should be :
$con = mysqli_connect(host,username,password,dbname);
And there will be a few modifications to the rest of your code
I advise you to follow PHP MySQL tutorial at : http://www.w3schools.com/Php/php_mysql_intro.asp
It is very simple and very straight forward and it will be a good start
. Also there is something called SQL injection you should be aware of when you are developing for production. But don't worry about it for now.
As of your question of how to get this data from DB. You will just create simple "SELECT .." and it will get all the data you need. If you follow w3schools tutorial you will find explaination of all of the steps you need to take
Thank you for your complement :). Find good resources on the internet and take your time and make great work.
I am trying to submit the page to itself but some reason the following code is not working. Also How can I get the table1 primary key ID back after inserting the data successfully? I have a child table which needs this ID. Thanks for any suggestions.
<?php
include('db_login.php');
$connection = mysql_connect( $db_host, $db_username, $db_password );
if (!$connection){
die ("Could not connect to the database: <br />". mysql_error());
}
// Select the database
$db_select=mysql_select_db($db_database);
if (!$db_select){
die ("Could not select the database: <br />". mysql_error());
if ($_POST['Submit'])
{
$first = $_POST["first"];
$first = mysql_real_escape_string(get_magic_quotes_gpc() ? stripslashes($first): $first);
$last = $_POST["last"];
$last = mysql_real_escape_string(get_magic_quotes_gpc() ? stripslashes($last): $last);
$insertsql = "INSERT INTO table1(FirstName,LastName) VALUES ('".$first."', '" .$last. "')";
$result1 = mysql_query($insertsql) or die(mysql_error());
}
?>
<form name="hotlineForm" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"
method="post">
<input id="first" type="text">
<input id="last" type="text">
<input type="submit" value="Submit"></form></body>
What part isn't working on the post back? Are you not entering your if statement?
To get the ID of the last insert use the following after your $result1 = mysql_query(...):
$primary_id = mysql_insert_id()
http://php.net/manual/en/function.mysql-insert-id.php
Change your form inputs to include name attributes. Without them, your $_POST will be empty.
<input name='first' id="first" type="text">
<input name='last' id="last" type="text">
<input name='Submit' type="submit" value="Submit">
As mentioned in the comments, get_magic_quotes should not be used. You've correctly called mysql_real_escape_string() on your inputs already.
Following your insert, get the id from mysql_insert_id():
$result1 = mysql_query($insertsql) or die(mysql_error());
$new_id = myqsl_insert_id();
if ($_POST['Submit'])
I don't see a form element with this name.
try:
if (isset($_POST['first']) && isset($_POST['last']))
For getting inserted ID you can use:
mysql_insert_id();
You are missing a closing } here:
if (!$db_select){
die ("Could not select the database: <br />". mysql_error());
} <<---- Close your if statement here.
if ($_POST['Submit'])
Currently the code that does the actual work only gets called if the DB cannot be selected.
Not very useful.
This is why proper indentation is important.
If you are religious about your indentation, you will spot these kind of errors instantly.
Use a name for the input field and check if it was sents not the submit