writing from a form to database - php

I have the following piece of code to make a input form being written in table named "client" database 'smsmart' which has fields name , address and phone
<?php
define ('DB_USER', 'root');
define ('DB_PASSWORD', '');
define ('DB_HOST', 'localhost');
define ('DB_NAME', 'smsmart');
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("smsmart");
if (!$db_selected) {
die('Can\'t use ' . smsmart . ': ' . mysql_error());
}
$value1 = $_POST['username'];
$value2 = $_POST['address'];
$value3 = $_POST['mobileno'];
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_close();
?>
The fields 'username' 'address' and 'mobileno' from form is not being written into database. What am i doing wrong?

It looks like you're generating the $sql query but not executing it. Given the lack of sanitation on your $_POST inputs, you should probably use a parametric or PDO method to protect yourself against potential SQL attacks.
Here is an example of a parameter-based mySQLi insert.
// connect to the database
$dbConnection = mysqli_connect("localhost", "root", "", "smsmart");
// prepare statement
$stmt = mysqli_prepare($dbConnection, "INSERT INTO client (name,address,phone) VALUES (?,?,?)");
// bind parameters
mysqli_stmt_bind_param($stmt, "sss", $value1, $value2, $value3);
// execute statement
mysqli_stmt_execute($stmt);
// close statement
mysqli_stmt_close($stmt);
// close database connection
mysqli_close($link);

You are saving your query in a variable but that variable isn't doing anything itself
mysql_query($sql);
mysql_query will help you to insert all the data in your Database.

you are missing mysql_query().
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_query($sql);
mysql_close();

$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_close();
hence add mysql_query
should be
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_query($sql);
mysql_close();

Everything looks great except one:
Just Use mysql_query() function, Like
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2',
'$value3')";
mysql_query($sql);
mysql_close();

Related

how to insert in to database using prepared statments in php

hello i am a java developer but new to php here i am trying to insert data in to the database using prepared statements as mentioned in here http://www.php.net/manual/en/pdo.prepared-statements.php but i am getting an error may i know what sort of error is this and any help to resolve this.
Error: Fatal error: Call to undefined method mysqli_stmt::bindParam() in G:****\xampp\htdocs****\registrationControl.php on line 17
<?php
$con = new mysqli("127.0.0.1", "root", "", "ksbka");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['username_first']);
$username_email = mysqli_real_escape_string($con, $_POST['username_email']);
$username_tele = mysqli_real_escape_string($con, $_POST['username_tele']);
echo $firstname."#####".$username_email;
$query="INSERT INTO instructorregistration (Id, Name, email, telephone) VALUES (?, ?, ?, ?)";
$pst = $con->prepare($query);
$pst->bindParam(1, "");
$pst->bindParam(2, $firstname);
$pst->bindParam(3, $username_email);
$pst->bindParam(4, $username_tele);
$pst->execute();
if (!mysqli_query($con,$pst)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
I think if you want to use bindParam() method, the value should be an instance of PDOStatement .
The doc you see as bellow:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$dbh is a PDO instance, I think, NOT mysqli instance. Because there is no mysqli::bindParam().
To solve this problem, you can:
use PDO class instead of Mysqli
create the query as the simplest way:
$query="INSERT INTO instructorregistration (Id, Name, email, telephone) VALUES (NULL, $firstname, $username_email, $username_tele)";
you have to use the mysqli methods, when you use mysqli
$stmt = $con->prepare($query);
$stmt->bind_param(1, "");
...
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
/* explicit close recommended */
$stmt->close();
/* Non-prepared statement */
$res = $mysqli->query("SELECT id FROM test");
var_dump($res->fetch_all());
edit: added some code from the official documentation

How to insert data into MySQL using MySQLi?

I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.

Unknow column in field list. Couldn't find what went wrong

This is the error that I got Error:Unknown column 'David Beckham' in 'field list'
I am stucked here for about 2 hours trying to figure what went wrong.
Anyone here mind to point out what's wrong with my code ?
Your help is greatly appreciated.
<?php
define('DB_NAME', 'testdb');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
//logon
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link){
die('Could not connect: '. msql_error());
}
// select the database you gonna work with
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Cant use' . DB_NAME . ':' . mysql_error());
}
$value = $_POST['FullName'];
$value2 = $_POST['Email'];
$value3 = $_POST['Postcode'];
$value4 = $_POST['DateofBirth'];
$value5 = $_POST['Gender'];
//insert into table.
$sql = "INSERT INTO vajayjay (FullName, Email, Postcode, DateofBirth, Gender) VALUES (`$value`, `$value2`, `$value3`, `$value4`, `$value5`)";
if(mysql_query($sql)){
echo "Thank you for signing up";
}else{
die('Error:'. mysql_error());
}
mysql_close();
?>
You are using backtrics for varibles.it is only for columns
$sql = "INSERT INTO vajayjay (`FullName`, `Email`, `Postcode`, `DateofBirth`, `Gender`) VALUES ('$value', '$value2', '$value3', '$value4', '$value5')";
USE backtrics for Column names
(`FullName`, `Email`, `Postcode`, `DateofBirth`, `Gender`)
USE Quotes for variables for escaping purpose
('$value', '$value2', '$value3', '$value4', '$value5')
Remove the backticks from the variables
The right way..
$sql = "INSERT INTO vajayjay (`FullName`, `Email`, `Postcode`, `DateofBirth`, `Gender`) VALUES ('$value', '$value2', '$value3', '$value4', '$value5')";
This(mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

SQL query is empty?

This php is suposed to send five attributes {id, description, email, price, shape} to the sales table in the salesinformation database.
<?php
define('DB_NAME', 'salesinformation');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Cannot connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Cannot use ' . DB_NAME . ': ' . mysql_error());
}
$value = $_POST['description'];
$value2 = $_POST['email'];
$value3 = $_POST['price'];
$value4 = $_POST['shape'];
$sql = mysql_query("INSERT INTO sales (id, description, email, price, shape) VALUES ('', '$value', '$value2', '$value3', '$value4')");
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
mysql_close();
?>
If I echo $value it prints out the correct information that I filled in my html form (So the part that extracts values from the HTML is working atleast). I run xampp and created the database with PhpMyAdmin, and when this PHP runs all I get is Error: Query was empty and nothing is added to the database at all.
What makes the mysql_query empty?
EDIT: I had missed a ' sign at one of the values.
Now instead I get this error message
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
Question: What makes the mysql_query empty?
It's you, who calls mysql_query without a real query:
$sql = mysql_query("INSERT INTO sales (id, description, email, price, shape) VALUES ('', '$value', '$value2', '$value3', '$value4')");
if (!mysql_query($sql)){ // <---- look here
die('Error: ' . mysql_error());
}
What we see in your code is that you pass $sql to mysql_query which isn't a valid query and you can check it with var_dump($sql);
Remove the ID column from your query. Assuming you made made it a INDEX (and AUTO_INCREMENT) probably:). You can either remove it out the fieldlist, or instead of the '' put a NULL there :).

Php Post to two tables in Mysql

I'm trying to POST to two tables at the same time. I'm trying to get the DonorID to display in to another table under $description. I'm able to just write any text in the $description, but I need it to be dynamic not static, which is what the text is. I have two tables; the first is accounting and the second is donations. I'm trying to alter the $description='Donation from Donor'; and have the donor that made the transaction be listed where the Donor is. Any suggestions would be greatly appreciated.
Here is my code:
<?php
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
$con = mysql_connect("$dbserver","$dblogin","$dbpassword");
if (!$con)
{
die('Could not connect to the mySQL server please contact technical support
with the following information: ' . mysql_error());
}
mysql_select_db("$dbname", $con);
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO accounting (date, transactiontype, account,
description, Income, Expense)
VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
mysql_query($sql2);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
header( 'Location: http://localhost/donations.php' ) ;
?>
As i said i would personaly use mysqli for new project, here a sample of you code with mysqli:
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
//opening connection
$mysqli = new mysqli($dbserver, $dblogin, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO `donations` (`date`, `firstname`, `middleinitial`, `lastname`, `organization`, `donorid`, `paymenttype`, `nonmon`, `Income`, `event`) Values ('$date','$firstname','$middleinitial','$lastname','$organization', '$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
$query1 = $mysqli->query($sql) or die($mysqli->error.__LINE__);
$query2 = $mysqli->query($sql2) or die($mysqli->error.__LINE__);
//closing connection
mysqli_close($mysqli);
header( 'Location: http://localhost/donations.php' ) ;
UPDATE
you can add donorid simply placing both vars in the query like:
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('".$date."','".$transactiontype."','".$account."','".$donorid . " " . $description."','".$Income."','".$Expense."')";
this way i just separate donorid and description with a space but you can add anything you want to in plain text:
'".$donorid . " - " . $description."'
After this
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
put
mysql_query($sql);
Please execute the query.
Things I see is ..
First your just executing your $sql2 but not the other $sql statement
Another is while inserting you declared some columns name that is a mysql reserved word (date column)
you should have `` backticks for them..
Refer to this link MYSQL RESEERVED WORDS
additional note: Your query is also vulnerable to sql injection
SQL INJECTION
How to prevent SQL injection in PHP?
Just write after insert on trigger on first table to insert data into another table.
You will have to split $sql2 to 2
1st :-
$sql2 = "INSERT INTO accounting (description) SELECT * FROM donations WHERE donorid='$donorid'"
then another one
"UPDATE accounting SET date='', transactiontype='', account ='', Income='', Expense ='' WHERE description=(SELECT * FROM donations WHERE donorid='$donorid')"
that will take all the information from donoation for the given donorid and list it under description in accounting

Categories