SQL query is empty? - php

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 :).

Related

writing from a form to database

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();

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

PHP process page does not work

Hi guys my process page does not work, my code is
<?php
$id = $_POST['item_id'];
$qty = $_POST['item_qty'];
$name = $_POST['item_name'];
$con = mysqli_connect ("localhost", "name", "password", "db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO Temp (id, qty, name)
VALUES
('$_POST[id]', '$_POST[qty]', '$_POST[name]')";
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error());
}
header('Location: http://url.com/');
mysqli_close($con);
?>
Should be all correct, just copy from w3school,
The problem is, the db only get 0,
ie. my $id is 4, $qty is 12, $name is "Hello", after the process page, the table only get two 0s in id and qty, name is void.
The values should be processed to this process page successfully, bc I have tried
echo $id, $qty, $name;
All are the same as I typed in before.
Could anyone help me? thanks :-)
this line:
INSERT INTO Temp (id, qty, name) VALUES ('$_POST[id]', '$_POST[qty]', '$_POST[name]')";
should be:
INSERT INTO Temp (id, qty, name) VALUES ('$id', '$qty', '$name')";
If the form is from your previous question, you dont need:
$id = $_POST['item_id'];
$qty = $_POST['item_qty'];
$name = $_POST['item_name'];
I agree it looks like you left out item_. You might want to sanitize your data first.
$id=mysqli_real_escape_string($_POST['item_id']);
$qty=mysqli_real_escape_string($_POST['item_qty']);
$name=mysqli_real_escape_string($_POST['item_name']);
$sql = "INSERT INTO Temp (id, qty, name)
VALUES ('$id', '$qty', '$name')";

Unable to update database using php

I have a the following code for inputing data in a database..i specifically echoed the values to see whether they have correct values or not...they have correct values but the values i get in the database are totally different.
Here is my code
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("sm_sample");
$source=$_POST['source'];
$username=$_POST['username'];
$location=$_POST['location'];
$category=$_POST['category'];
$complaint=$_POST['complaint'];
$status=$_POST['status'];
$date=$_POST['date'];
echo $source.$username.$location.$category.$complaint.$status.$date;
$sql="INSERT INTO sample VALUES(ID=NULL,source='$source',username=
'$username', location='$location', category='$category',complaint=
'$complaint',date='$date',status='$status')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
echo "<BR>";
echo "<a href='usercom1.php'>View result</a>";
mysql_close($con)
?>
the values i get in the database r like this:
List data from mysql
Source Username Location Category Complaint Date Status Update
0 Singapore 0 0000-00-00 Pending Edit
The correct syntax:
$sql="INSERT INTO `sample`(`ID`,`source`,`username`, `location`,`category`,`complaint`,`date`,`status`)
VALUES (0, '$source','$username','$location','$category','$complaint','$date','$status')";
later edit ... you are using wrong mysql_query and connection syntax
$con = mysql_connect("localhost","root","") or die('database connection?');
mysql_select_db("sm_sample", $con) or die('wrong database?');
// and for $_POST you sould use mysql_real_escape_string
$source = mysql_real_escape_string($_POST['source']);
// ........................................
$sql="INSERT INTO `sample`(`ID`,`source`,`username`, `location`,`category`,`complaint`,`date`,`status`)
VALUES (0, '$source','$username','$location','$category','$complaint','$date','$status')";
mysql_query($sql) or die('Error: '.mysql_error().': '.mysql_errno());
// ........................................
mysql_close($con);
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
echo ('Could not connect: ' . mysql_error());
}
mysql_select_db("sm_sample",$con);
$source=$_POST['source'];
$username=$_POST['username'];
$location=$_POST['location'];
$category=$_POST['category'];
$complaint=$_POST['complaint'];
$status=$_POST['status'];
$date=$_POST['date'];
echo $source.$username.$location.$category.$complaint.$status.$date;
$sql="INSERT INTO sample ('source','username','location','category','complaint','status') VALUES('$source','$username','location','category','complaint','status' )";
if (!mysql_query($sql))
{
echo ('Error: ' . mysql_error());
}
echo "1 record added";
echo "<BR>";
echo "<a href='usercom1.php'>View result</a>";
mysql_close($con);
?>
First thing you do not have to add id if it is auto increment and date if it uses current timestamp and one more thing that never use die(); , use echo instead.
You should provide only VALUES of data with no column names:
$sql="INSERT INTO sample VALUES(ID, '$source', '$username', '$location', '$category', '$complaint', '$date', '$status')";
Also if you have only one DB connection you can not to define $con variable in mysql_query(). Like this: mysql_query($sql).
The problem is with the following line:
<?php
$sql="INSERT INTO sample VALUES(ID=NULL,source='$source',username='$username', location='$location', category='$category',complaint=
'$complaint',date='$date',status='$status')";
?>
If you check the result in the database, you'll see that the values are getting in the wrong order, use this instead:
<?php
$sql="INSERT INTO sample(ID, source, username, location, category, complaint, date, status) VALUES(NULL, '$source', '$username', '$location', '$category', '$complaint','$date','$status')";
?>
PLEASE read what Albireo posted in his comment. Your code is extremely vulnerable.

Error when inserting into SQL table with PHP

This is my code:
function function() {
$isbn = $_REQUEST["isbn"];
$price = $_REQUEST["price"];
$cond = $_REQUEST["cond"];
$con = mysql_connect("localhost","my_usernam", "password");
if (!$con) die('Could not connect:' . mysql_error());
mysql_select_db("my_database",$con);
$sql="INSERT INTO 'Books' (isbn, price, condition)
VALUES ('$isbn','$price','$cond')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
return "It works";
But when run it results in:
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 ''Books' (isbn, price....
Anyone know why this is happening?
You should use backticks instead of single quotes for table and field names:
$sql="INSERT INTO `Books` (`isbn`, `price`, `condition`)
VALUES ('$isbn','$price','$cond')";
will work.
ps. to prevent all kinds of nasty security holes, escape the input fields with:
$isbn = mysql_real_escape_string($_REQUEST["isbn"]);
// etc etc for all fields
Wrap table names in backticks, not quotes, and make sure to escape your input for security:
$sql="INSERT INTO `Books` (`isbn`, `price`, `condition`)
VALUES ('" . mysql_real_escape_string($isbn) . "',
'" . mysql_real_escape_string($price) . "',
'" . mysql_real_escape_string($cond) . "')";

Categories