insert into a database not working - php

I am having an issue in inserting into a table. The connection file is correct and is coming from the header.php. There are no errors but when I go within the table no records are being inserted.
<?php
include('header2.php');
if(isset($_POST['done'])) {
$title = $_POST['title'];
$description = $_POST['description'];
$link = $_POST['link'];
$company = $_POST['company'];
$sql = "INSERT INTO placements (title, description, link, company)
VALUES ('$title', '$description', '$link','$company')";
// use exec() because no results are returned
echo "New record created successfully";
}
?>
<html>
<head>
<title> Add a Placement </title>
</head>
<body>
<form method="post">
<input type="text" name="title" placeholder="title">
<input type="text" name="description" placeholder="description">
<input type="text" name="company" placeholder="company">
<input type="text" name="link" placeholder="link">
<input type="submit" name="done">
</form>
</body>
</html>

You are not executing the query at all. I assume your database connection as below and run your query. It should work.
Tested.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['done'])) {
$title = $_POST['title'];
$description = $_POST['description'];
$link = $_POST['link'];
$company = $_POST['company'];
$sql = "INSERT INTO placements (title, description, link, company)
VALUES ('$title', '$description', '$link','$company')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}

Related

Save login form data using php

html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.
my html code
<html>
<head>
<title>Yahoo Signin And Signup Form</title>
</head>
<body>
<h2 style="color: midnightblue">yahoo!</h2>
<hr color="magenta">
<form method="post" action="connect.php" >
<fieldset style="background:#6495ED;">
<legend style="padding:20px 0; font-size:20px;">Signup:</legend>
<label for ="firstName">Enter First Name</label><br>
<input type="text" placeholder="First name" id="firstName" name ="firstName">
<br>
<label for ="lastName">Enter Last Name</label><br>
<input type="text" placeholder="Last name" id="lastName" name ="lastName">
<br>
<label for ="email">Enter Email</label><br>
<input type="text" placeholder="Email" id="email" name ="email"><br>
<label for ="password">Enter Password</label><br>
<input type="password" placeholder="Password" id="password" name ="password">
<br>
<label for ="number">Enter Mobile Number</label><br>
<input placeholder="03---" id="number" name ="number"><br>
<label for ="date">Enter Date of Birth</label><br>
<input type="text" placeholder="DD/MM/YY" id="date" name ="date"><br>
<label for ="gender">Enter Gender</label><br>
<input type="text" placeholder="Male/Female/Other" id="gender" name
="gender"><br>
<br><button style="background-color:orangered;border-
color:dodgerblue;color:lightyellow">Signup</button>
</fielsdet>
</form>
</body>
</html>
my connect.php
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
number, date, gender)
values(?,?,?,?,?,?,?)");
$stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
$number, $date, $gender);
$stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
}?>
Use prepare instead of query. All everything is ok.:
$stmt = $con->prepare("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)");
And make button type as submit:
<br><button type="submit" style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
here is the code, it works fine with me
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values("'.$firstName.'","'.$lastName.'","'.$email.'","'.$password.'","'.$number.'","'.$date.'","'.$gender.'")");
if ($con->query($stmt) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$con->close();
}//end of else of connection
?>
Add type in your submit button.
<button type='submit' style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
and also your question marks and params ara not matching. it should be match. otherwise data won't store your db
correct that line also
The main problem is you are not loading code via apache server try to open http://localhost/signup.html instead of C:/xmapp/htdocs/connect.php
It seems you want to user PDO but your connection string not correct
<?php
$firstName = trim($_POST['firstName']);
$lastName = trim($_POST['lastName']);
$email = trim($_POST['email']);
$password = md5(trim($_POST['password']));
$number = trim($_POST['number']);
$date = trim($_POST['date']);
$gender = trim($_POST['gender']);
$con= new PDO("mysql:host=127.0.0.1;dbname=phpdata", 'root', 'root');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqli = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)";
try {
$stmt= $con->prepare($sqli);
$stmt->bindParam(1,$firstName);
$stmt->bindParam(2,$lastName);
$stmt->bindParam(3,$email);
$stmt->bindParam(4,$password);
$stmt->bindParam(5,$number);
$stmt->bindParam(6,$date);
$stmt->bindParam(7,$gender);
$status = $stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
} catch(PDOException $e) {
echo "Error ".$e->getMessage();
}
?>
another problem is with your html form button type is missing
<button type="submit".... />
Here is the complete code after analyzing it for a lot of time. in your $stmt variable there was no query, it was empty. This code works fine just copy and paste it.
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','abc');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$sql = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values('$firstName','$lastName','$email','$password','$number','$date','$gender')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
}//end of else of connection
?>

mysqli insertion query neither insert records nor shows the location of error

I'm trying to execute an sql query that insert a record into a database on WAMP server, but when after pressing the submit button on form, that calls the php code, nothing happens. it just shows the message "Record insertion failed" i provided in the script. after trying and searching for a period of time, i'm unable to find WHERE IS THE ERROR IN QUERY. the code is give below:
<?php
$server="localhost";
$user="root";
$password="";
$database="dbname";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//variables getting values from HTML form
if(isset($_POST['Submit-Personal'])){
$name = $_POST['name'];
$cnic = $_POST['cnic'];
$date = $_POST['booking-date'];
$ocassion = $_POST['ocassion'];
$address = $_POST['address'];
$phoneno = $_POST['phone-no'];
$bridemobile = $_POST['bride-mobile'];
$groommobile = $_POST['groom-mobile'];
$familymobile = $_POST['family-mobile'];
$email = $_POST['email'];
$refering = $_POST['refering'];
$share = $_POST['share'];
$permission = $_POST['permission'];
// attempt insert query execution
$qry = "insert into personal_detail (Name, CNIC, Date, Ocassion, Address,
Phone_No, Bride_Mobile, Groom_Mobile,
Family_Mobile,EMail,Referring,Share,Permission) values
('$name','$cnic','$date','$ocassion','$address','$phoneno','$bridemobile','$gro
ommobile','$familymobile','$email','$refering','$share','$permission')";
if(mysqli_query($con,$qry))
{
$message = "Record Saved Successfully";
echo "<script type='text/javascript'>alert('$message');</script>";
}
else
{
$message = "Record Insertion Failed!";
echo "<script type='text/javascript'>alert('$message');</script>";
}
I have another table it's working completely fine. Means saves records into the table if the entries in the form are made as required.To me the syntax of both is looking completely same, but don't why the one not working: the PHP code that' working fine for other table is given below:
<?php
$server="localhost";
$user="root";
$password="";
$database="camouflage_studio";
$con = mysqli_connect($server,$user,$password,$database);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$cn = $_POST['contact-number'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
//query
$qry = "insert into contact_us (Name,Contact_No,EMail,Subject,Message) values ('$name','$cn','$email','$subject','$message')";
if(mysqli_query($con,$qry))
{
$message = "Record Saved Successfully";
echo "<script type='text/javascript'>alert('$message');</script>";
}
else
{
$message = "Record Insertion Failed!";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
mysqli_close($con);
?>
#Muhammad Aatif here i have a similar example of your with same column and table name.
I have used mysqli_real_escape_string($conn, $_POST['name_of_form']) against SQL INJECTION to know more you can visit this site sql injection link
HERE IS THE HTML FORM CODE IN FILE NAME: INDEX.PHP
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<form action="process.php" method="post">
<p>enter name</p>
<input type="text" name="name"><br>
<p>enter cnic</p>
<input type="text" name="cnic"><br>
<p>enter data</p>
<input type="date" name="date"><br>
<p>enter Occassion</p>
<input type="text" name="ocassion"><br>
<p>enter Address</p>
<input type="text" name="address"><br>
<p>enter phone_no</p>
<input type="text" name="phone_no"><br>
<p>enter Bride mobil</p>
<input type="text" name="bride_mobile"><br>
<p>enter Groom mobile</p>
<input type="text" name="groom_mobile"><br>
<p>enter family mobile</p>
<input type="text" name="family_mobile"><br>
<p>enter email</p>
<input type="text" name="email"><br>
<p>enter Referring</p>
<input type="text" name="referring"><br>
<p>enter share</p>
<input type="text" name="share"><br>
<p>enter permission</p>
<input type="text" name="permission"><br>
<input type="submit" name="Submit-Personal"><br>
</form>
</body>
</html>
HERE IS THE PHP CODE IN FILE NAME: PROCESS.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['Submit-Personal'])){
$name = mysqli_real_escape_string($conn, $_POST['name']);
$cnic = mysqli_real_escape_string($conn, $_POST['cnic']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$ocassion = mysqli_real_escape_string($conn, $_POST['ocassion']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$phone_no = mysqli_real_escape_string($conn, $_POST['phone_no']);
$bride_mobile = mysqli_real_escape_string($conn, $_POST['bride_mobile']);
$groom_mobile = mysqli_real_escape_string($conn, $_POST['groom_mobile']);
$family_mobile = mysqli_real_escape_string($conn, $_POST['family_mobile']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$referring = mysqli_real_escape_string($conn, $_POST['referring']);
$share = mysqli_real_escape_string($conn, $_POST['share']);
$permission = mysqli_real_escape_string($conn, $_POST['permission']);
$sql = "INSERT INTO personal_detail (Name,CNIC, Date,Ocassion,Address,Phone_No,Bride_Mobile,Groom_Mobile,Family_Mobile,EMail,Referring,Share,Permission) VALUES ('$name','$cnic','$date','$ocassion','$address','$phone_no','$bride_mobile','$groom_mobile', '$family_mobile','$email','$referring','$share','$permission')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
echo "<script type='text/javascript'>alert('sucess');</script>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
HERE IS THE OUTPUT RESULT
HERE IS THE TABLE IMAGE
FEEL FREE TO ASK MORE QUESTIONS
The proper way to prevent sql injection is to use MYSQLI->PREPARED STATEMENT CLICK ON THIS LINK TO GET BREIF DETAIL SQL INJECTION

when i insert data in db i get num1 in all column

i try to creat a table with html and php
when i insert data into my db i get num 1 like a values in all column
this my code
<html dir="rtl">
<form action="" method="post">
<label for="Nom">الاسم:</label>
<center><input type="text" name="Nom"></center>
<label for="Cin">البطاقة الوطنية:</label>
<center><input type="text" name="Cin"></center>
<label for="Tel">الهاتف:</label>
<center> <input type="text" name="Tel"></center>
<label for="DATE_donation"> تاريخ التبرع:</label>
<center><input type="date" name="DATE_donation"></center>
<center><input type="submit" value="إدخال"></center>
</form>
</html>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ikhlas";
$con= mysqli_connect($servername, $username, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$Name =isset($_POST['Nom']);
$CIN = isset($_POST['Cin']);
$TEL = isset($_POST['Tel']);
$date = isset($_POST['DATE_donation']);
$sql="INSERT INTO persone(Nom, Cin, Tel, DATE_donation) value ('$Name','$CIN','$TEL','$date')";
if (mysqli_query($con, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
?>
and this my ressult in dbenter image description here
Sure because you define all variable with $foo = isset($bar) instead of
if(isset($bar))
$foo = $bar;
Take a look to the doc about SQL injection too: http://php.net/manual/en/security.database.sql-injection.php
Remove your isset()
http://php.net/manual/en/function.isset.php
Replace to:
if(isset($_POST['إدخال']))
{
$Name = (!empty($_POST['Nom']))?$_POST['Nom']:"";
$CIN = (!empty($_POST['Cin']))?$_POST['Cin']:"";
$TEL = (!empty($_POST['Tel']))?$_POST['Tel']:"";
$date = (!empty($_POST['DATE_donation']))?$_POST['DATE_donation']:"";
}

Get and insert Data into MySQL database using PHP with xampp on localhost

I have managed to connect to database and I manage to insert using following code.
<?php
$username = 'root';
$password = '';
$db = 'demo';
$conn = new mysqli ('localhost',$username, $password, $db) or die("unable to connect");
$sql="insert into persons (first_name,last_name,email_address) values ('sara','smith','email#email.com')";
$query=mysqli_query($conn,$sql);
if($query)
echo 'data inserted';
?>
But the problem is that when I try to enter data using HTML form, it didn't work for me. I have tried to follow different tutorials and different answers here on stackoverflow. Can anyone please tell me the easiest way of inserting and getting data from MySQL using PHP ?
If there is any easy tutorial or blog from where i can learn and understand all this, I would love to watch or read.
I manage to do it in following way.
Create a file name index.php with following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
Then create another file name as insert.php
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
// attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
//procedural style
$mysqli = mysqli_connect('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//inserting a record
$product_code = '"'.$mysqli->real_escape_string('P1234').'"';
$product_name = '"'.$mysqli->real_escape_string('42 inch TV').'"';
$product_price = '"'.$mysqli->real_escape_string('600').'"';
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO products (product_code, product_name, price) VALUES($product_code, $product_name, $product_price)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
A quick and untested example of using an HTML form with the POST method to insert data entered by a user into the db.
<?php
$result = false;
$dbhost = 'localhost';
$username = 'root';
$password = '';
$db = 'demo';
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$conn = new mysqli ( $dbhost,$username, $password, $db );
if( $conn ){
$sql='insert into `persons` ( `first_name`,`last_name`,`email_address` ) values (?,?,?);';
$stmt=$conn->prepare( $sql );
$stmt->bind_param('sss', $_POST['firstname'], $_POST['lastname'], $_POST['email'] );
$result = $stmt->execute();
}
$conn->close();
}
?>
<!doctype html>
<html>
<head>
<title>Simple Form submission example</title>
</head>
<body>
<form method='post'>
<input type='text' name='firstname' />
<input type='text' name='lastname' />
<input type='text' name='email' />
<input type='submit' value='Submit' />
<?php
echo $result ? '<div>The database was updated</div>' : '';
?>
</form>
</body>
</html>
Try tutsplus or lynda, Provide you with the best tuto !

Why this code inserts blank?

I´m trying to create a form connected to a database but when I fill out the form and I refer to the table in phpMyAdmin I see that it have entered a blank record instead of form data. I´m using PhpStorm.
I think all this code is correct...
That is the form of the .html:
<form id="form1" name="form1" method="post" action="index.php">
<label for="userSignUp">Email</label>
<input type="text" name="userSign" id="userSignUp" />
<label for="passwordSignUp">Password</label>
<input type="password" name="passwordSign" id="passwordSignUp" />
<input type="submit" name="Submit" id="Submit" value="Submit" />
</form>
I have the following .php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$db_selected = mysqli_select_db($conn, $dbname);
$userSignUp = ""; // If I substitute "" with characters at this time the table is well updated
$passwordSignUp = ""; // Same as before
if(isset($_POST['userSign'])){
$userSignUp = $_POST['userSign'];
}
if (isset($_POST['passwordSign'])) {
$passwordSignUp = $_POST['passwordSign'];
}
$sql = "INSERT INTO test.person (FirstName, Password) VALUES ('$userSignUp', '$passwordSignUp')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();

Categories