Inserting data into MySQL database - php

I'm struggling with inserting data from the form to database. I managed to establish the connection (at least not getting any errors), but when comes to inserting values I facing error, I'm not sure if rows/columns of the table should be in ' ' or not, I've seen some examples both with quotation marks and without, and also if variables should have those as well.
connecting to the database (connect.php):
<?php
define("DB_SERVER","localhost");
define("DB_USER","root");
define("DB_PASS","");
define("DB_NAME","Bookshop");
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$connection){
die("error: unable to connect to database " . mysql_error());
}
$select_db = mysql_select_db(DB_NAME, $connection);
if(!$select_db){
die("error: unable to connect to database " . mysql_error());
}
?>
including connections:
<?php
include ("connect.php"); // connects to database
?>
and inserting data from the form:
$query = "INSERT INTO customer
(CUST_ID, CUST_NAME, CUST_SURNAME, HOUSE_NO, STREET, POSTCODE, PHONE_NO, EMAIL, OGIN, PASSWORD)
VALUES
('10101', '$forename', '$surname', '$address1', '$address2', '$postcode',
'$phone_no', '$email', '$login', '$password')";
mysql_query($query, $connection);
if(!mysql_query($query, $connection)){
echo "Error!!!!";
}
mysql_close($connection);

It seems you are a newbie.. Start with mysqli or pdo extensions. Visit W3schools.com for a detailed explanantion with examples. Below is an example of how to use mysqli to connect and insert a row in your database
<?php
$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());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
And For your query..
I'm not sure if rows/columns of the table should be in ' ' or not,
I've seen some examples both with quotation marks and without, and
also if variables should have those as well.
As far as insert queries are concerned,
1).Wrap up column names with ` back ticks.
2).Wrap your Variables with single quote nothing wrong in that
For more understanding about single and double quote usages,
Single quotes does not look for variables while double quote does
Case 1 :
$value = 10;
$sql = 'SELECT * FROM `table_name` WHERE `column_name` = $value';
echo $sql;
output is
SELECT * FROM `table_name` WHERE `column_name` = $value
Here if you see single quote does not look for a variable within it. Whatever there is inside single quotes, it is considered as a string and returned as such.
Case 2:
$value = 10;
$sql = "SELECT * FROM `table_name` WHERE `column_name` = $value";
echo $sql;
Output is
SELECT * FROM `table_name` WHERE `column_name` = 10
Here Since the query is inside double quotes, That variable is read. but considered as int.
Case 3:
$value = 10;
$sql = "SELECT * FROM `table_name` WHERE `column_name` = '$value'";
echo $sql;
Output is
SELECT * FROM `table_name` WHERE `column_name` = '10'
Here Since the query is inside double quotes, That variable is read. but considered as string as it is encapsulated with single quotes.

Related

cant insert data into existing table in mysql database with php

I get the message that the new record was created but when I reload phpmyadmin the table is the same. Also I have retrieved information from the same DB,
from the same table, with SELECT command, so the connection works..(plainly said). I have no clue why is not updating. Please help. Thank you in advance.
<html>
<head>
</head>
<body>
<?php
define('DB_NAME', 'appointments');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$hos=$_POST['hos'];
echo $hos;
echo "<br/>";
$doc=$_POST['doc'];
echo $doc;
$date=$_POST['fdate'];
echo $date;
$time=$_POST['time'];
echo $time;
$pat=5;
echo $pat;
$sql = "INSERT INTO rantevou ('app_id','patient_id','date','time','hos','doc') VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($sql) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($link);
?>
</body>
</html>
There are many mistake in your code
1. use of mysql_error()
you can't use mysql_error because you use mysqli for data base connection.second thing mysql is no more supported
Solution use mysqli_error($link);
2. use of $conn->error
You can't us of $conn->error beacuse you connect with mysqli procedure way not like object oriented way and you also not define a $conn instead you used $link
Solution use mysqli_error($link);
Correct Code
if(!mysqli_query($link, $sql)){
printf("Errormessage: %s\n", mysqli_error($link));
die;
}else{
echo "New record created successfully";
}
Why Data Not Inserted
because you declare variable $sql but you didn't executed that
the new record was created
You get this message all ways because your if condition check that variable have a value (not 0) and yes $sql have value
1.You must use prepare statement,if you don't wan't any sql injection in insert statement SQL INJECTION
2.'' single quote or "" apply only on a string not on id if your app_id is a int don't use ('' or "") quote instead of that convert '4' to int
3.handle error log https://stackoverflow.com/a/3531852/3234646
4.Please clear Concept use of Database Extension
http://php.net/manual/en/class.mysqli.php
You forgot to execute the query, if ($sql) { merely evaluates the variable.
if (mysqli_query($link, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Also, you need to use backticks for SQL-related variables, not single quotes:
$sql = "INSERT INTO rantevou (`app_id`,`patient_id`,`date`,`time`,`hos`,`doc`) VALUES ('4','$pat','$date','$time','$hos','$doc');";
You're not actually executing your query. If you add the line $result = mysqli_query($link, $sql); after declaring $sql you will execute the query.
You can then assess whether it worked using the same if, but change that line to be
if ($result) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($link);
}
In the above example, I have also changed your error reporting as it was referencing $conn, a variable you had not declared before. It now uses the same $link variable as the rest of your code.
Also, I would highly recommend escaping your data since you're inserting the contents of posted data. Escaping your data will help protect against SQL Injection. It's not comprehensively safe, but it's a good start.
To add in escaping, change each $var = $_POST['var'] line to read $var = mysqli_real_escape_string($link, $_POST['var']);
For example, $hos=$_POST['hos']; becomes $hos = mysqli_real_escape_string($link, $_POST['hos']);
This helps prevent moments like this wonderful example by XKCD
1) Remove single quotes (') from column name to backtick (`)
2) Execute your query. You didn't executed.
3) If app_id column is auto incremented and primary key. Then, no need to pass value. Leave it blank.
<?php
$sql = "INSERT INTO rantevou (`app_id`,`patient_id`,`date`,`time`,`hos`,`doc`) VALUES ('','$pat','$date','$time','$hos','$doc');";
$query = mysqli_query($link,$sql) ;
if ($query) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Instead of
"INSERT INTO rantevou ('app_id','patient_id','date','time','hos','doc') VALUES ('4','$pat','$date','$time','$hos','$doc');"
unquote the columns
"INSERT INTO rantevou (app_id, patient_id, date, time, hos, doc) VALUES ('4','$pat','$date','$time','$hos','$doc');"
or use backticks
"INSERT INTO rantevou (`app_id`, `patient_id`, `date`, `time`, `hos`, `doc`) VALUES ('4','$pat','$date','$time','$hos','$doc');"
you've forgot to execute your query
mysqli_execute($con, "INSERT INTO rantevou (`app_id`, `patient_id`, `date`, `time`, `hos`, `doc`) VALUES ('4','$pat','$date','$time','$hos','$doc')");
EDIT: What luweiqi said: the statement has yet to be executed!
It seems like you know what you are doing. Are you sure that the paramaters here:
$sql = "INSERT INTO rantevou (**'app_id','patient_id','date','time','hos','doc'**) VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($sql) {
exactly match your column titles in your database?
Another good way to check your statements, is to go to phpmyadmin and go to the SQL notepad and enter the query with the same structure and see what is being returned.
Your query may be returning a message, but a message saying that it has failed... which would still trigger your echo "New record created successfully";
This is how i've structured my most recent insert to DB:
<?php
// to get data from android app
$gardenID=$_POST["gardenID"];
$vID=$_POST["vID"];
$quantity = $_POST["quantity"];
$timePlanted = date("Y/m/d");
// establishes connection to database
require "init.php";
echo "here";
echo $timePlanted;
echo $quantity;
$query = "insert into garden_veg (gardenID, vID, quantity, timePlanted) values ('".$gardenID."','".$vID."',
'".$quantity."', '".$timePlanted."' );";
$result = mysqli_query($con,$query);
$response = array();
$code = "addItem_success"; //changed code
$message = "Item(s) added!";
array_push($response,array("code" => $code, "message"=>$message));
echo json_encode(array("server_response"=>$response));
mysqli_close($con);
?>
First of all, don't use single quotes for column names, either use nothing or use backticks.
Secondly, you forgot to execute the query.
Also, using OOP is better.
Please try:
$mysqli = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
and
$query = "INSERT INTO rantevou (app_id,patient_id,date,time,hos,doc) VALUES ('4','$pat','$date','$time','$hos','$doc');";
if ($mysqli->query($query)) echo "New record created";
else echo "Error: ".$mysqli->error;

PHP insert into not inserting any data

I have a php statement to insert a bit of information into my mySQL database. the connection works perfectly. The problem I am having is I am getting the following error code:
Error: INSERT INTO tasks ('taskName', 'requestedBy', 'details',
'dateAdded') VALUES ('test1' ,'test3' ,'test3', 2015-01-05') 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 ''taskName',
'requestedBy', 'details', 'dateAdded') VALUES ('test1' ,'test3' ,'te'
at line 1
the function is as follows
if(isset($_POST["submitTask"])){
insertTask();
};
function insertTask(){
$servername = "localhost";
$username = "tasktrack";
$password = "";
$dbname = "tasktrack";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$taskname = $_POST["task_name"];
$requestedby= $_POST["requested_by"];
$details = $_POST["details"];
$datenow = date("Y-m-d");
$sql = "INSERT INTO tasks ('taskName', 'requestedBy', 'details', 'dateAdded') VALUES ('$taskname' ,'$requestedby' ,'$details', $datenow')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
};
I have tried multiple different solution with the $sql line as seen below
$sql = "INSERT INTO tasks ('taskName', 'requestedBy', 'details', 'dateAdded') VALUES ('$taskname' ,'$requestedby' ,'$details', $datenow')";
$sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ($taskname ,$requestedb ,$details, $datenow)";
$sql = "INSERT INTO tasks (`taskName`, `requestedBy`, `details`, `dateAdded`) VALUES (`$taskname` ,`$requestedb` ,`$details`, `$datenow`)";
Now I am just stuck and can't think of any more things to try.
$sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')";
// Removed quotes from columns, and added missing quote on datenow
Please note, this technique for adding values into the database is very insecure, and is prone to SQL injection attacks.
You must not enclose the field names in apostrophes or quotes. Either enclose them in back quotes (`) or use them as they are.
$sql = "INSERT INTO tasks (`taskName`, `requestedBy`, `details`, `dateAdded`) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')";
or
$sql = "INSERT INTO tasks (taskName, requestedBy, details, dateAdded) VALUES ('$taskname' ,'$requestedby' ,'$details', '$datenow')";
However, if the field name is a MySQL keyword or if it contains spaces, quotes, commas, parenthesis, operators or other characters that have special meaning in SQL then you have to enclose them in back quotes or MySQL will report a syntax error at the special character.

Can't insert into to my Database with PHP

I want to insert some info into a table but it doesn't works. This is the code.
<?php
$con=mysql_connect("localhost","Chew","*****","Birthdays");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Name="Something";
$Desc="Something";
$Lang="En";
$D="1";
$M="1";
echo "<br>";
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, Day, Month) VALUES ('".$Name."', '".$Desc."', '".$Lang."', '".$D."', '".$M."' );";
$qr= mysql_query($con, $sql) or die("Error: " . mysql_error());
mysql_close($con);
?>
MONTH and DAY are names of MySQL functions. If you are going to name columns with those names you must escape them with ticks:
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, `Day`, `Month`) VALUES ('".$Name."', '".$Desc."', '".$Lang."', '".$D."', '".$M."' );";
read mysql_query
$qr= mysql_query($sql, $con) or die("Error: " . mysql_error());
NB: mysql_* is deprecated, use mysqli_* or pdo
If D and M are numbers, your SQL should not use quotes (') in the VALUES-part of your SQL
You should be using Object Oriented mechanism for doing connection with MySQL with the help of MySQLi class
example
// The var's in complete caps means they might be defined as constant variable
// DB_HOST - database hostname
// DB_USER - database user
// DB_PASS - database password
// DB_NAME - database instance name
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($db -> connect_error){
// in case there are errors
die("Connect Error (" . $db -> connect_errno . ") " . $db -> connect_error);
}
$Name= mysql_real_escape_string("Something"); // helps to escape special characters like quotes
$Desc= mysql_real_escape_string("Something");
$Lang="En";
$D="1";
$M="1";
$sql = "INSERT INTO `Birthdays` (Name, Description, Language, `Day`, `Month`) VALUES ('".$Name."', '".$Desc."', '".$Lang."', $D, $M );";
$db -> query($sql) or die("Error: " . $db -> error_msg);
echo "Insert id: " . $db -> insert_id;
EDIT: Code to fetch data from database
C_Chewbacc,
I would recommend you on reading more on PHP-MySQL connection using Object Oriented mechanism
http://in2.php.net/mysqli
Try this code below
$sql = "SELECT * FROM Birthdays";
$result = $db -> query($sql); // SELECT query returns result object here
// We iterate over this result object and fetch each row on every iteration
// When the resultant object has nothing to return, NULL is initialised in $row
// When $row = NULL becomes the exit point of WHILE loop
while($row = $db -> fetch_array($result)){
var_dump($row); // This will display every row of data
}

I can add a string literal to my table but if I pass a string as a variable it only works with numbers

I have a simple mysql table
This is the code to connect to database and insert into testtable:
$mysqli = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$sql = "INSERT INTO testtable
VALUES (NULL, $forename)";
$res = mysqli_query($mysqli, $sql);
if($res === TRUE) {
echo "data successfully inserted.";
} else {
printf("Could not insert data: %s\n", mysqli_error($mysqli));
}
mysqli_close($mysqli);
}
In this case I try to insert $forename into my table. If I use a string literal like 'Jim' or '123' it gets inserted. If $forename is given the value 123 or any other number it gets inserted. If $forename = 'Jim' I get an error telling me there is no column 'Jim' as though I were specifying a column in the table.
It has happened to me before, you are missing quotes in the query. Try:
$sql = "INSERT INTO testtable VALUES ('{$forename}')";
When forename is 'Jim', the query expands to ".... VALUES(NULL, Jim)", but you want "... VALUES(NULL, 'Jim')". Your query should read "...VALUES(NULL, 'Jim')".
use a prepared statement
$db= mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$sql = "INSERT INTO testtable (testfield) VALUES (?)";
if ($statement =$db->prepare($sql)){
$statement->bind_param("s",$forename);
msqi_stmt_execute($statement);
};
Since your id field is an autonumber, you don't need to insert anything. You should also really get in the habit of specifying the columns to insert into:
Instead of :
INSERT INTO testtable VALUES (NULL, $forename)
use:
INSERT INTO testtable
(
`testfield`
)
VALUES
(
'$forename'
)
Note that the "quotes" around the field name are back-ticks, not single quotes.
Of course, using string insertion like this is a security risk, so you really should be using prepared statements, as case1352 demonstrates in his answer.

php insert mysql not working

.I don't know if it's syntax or what. I've tried a variety of ways this is the simplest I thought would work.
I send info to the userData.php using:
http://mydomain.com/adverts/userStats.php?name=001EC946C2F4&adNum=1&playClick=1
On the userData.php I have:
<?php
$db = mysql_connect('localhost', 'username', 'password') or die('Could not connect: ' . mysql_error());
$db_selected = mysql_select_db('databaseName', $db) or die('Could not select database');
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
$name = mysql_real_escape_string($_GET['name']);
$date = date("d/m/Y");
$adClick = mysql_real_escape_string($_GET['adNum]);
$playN = mysql_real_escape_string($_GET['playClick']);
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
mysql_close($db);
?>
I manually added 2 records to the table from phpMyAdmin, and I can display or update them just fine but adding a new record isn't working. I simply want to start a new record each time the link is called from another program, and store the mac address, date, adNum, and playClick.
EDIT2:: echo $query; for
http://simplehotkey.com/adverts/userStats.php?name=001EC946C2F4&adNum=1&playClick=1
outputs:
INSERT INTO playerData(mac,date,AdClick,PlayNum) VALUES ('001EC946C2F4', '26/07/2012','1','1')
Which is what I want it's just not adding it to the DB.
Correct syntax is --
mysql_select_db("databaseName", $db);
And its better if u use something like this for connection errors--
$db_selected= mysql_select_db("databaseName", $db);
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
EDIT
You are writing all wrong :(
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) <--------------WRONG
Try Something like this----
$query = "INSERT INTO playerData(CORRECT_COL_NAMES) VALUES ('$name', '$date','$adClick','$playN')";
$results = mysql_query($query, $connection);
NEW EDIT
AREA OF ERROR---- WRONG DATATYPE
','1','1' <--- this is passing as string while u have have this as an int in your db structure ..now run the same query as it is to figure out the error..also u can figure out using $result = mysql_query($query) or die(mysql_error());
It's pretty easy to see what's wrong here, especially with syntax highlighting.
$adClick = mysql_real_escape_string($_GET['adNum]);
This line is missing a single quote mark; it should be:
$adClick = mysql_real_escape_string($_GET['adNum']);
This is a syntax error that ruins everything else.
Not to mention that your database selection is missing your database handler, ie:
mysql_select_db('databasename',$db);
As pointed out by #swapnesh, and as noted here.
Edit
I have been unable to reproduce your lack of an error, what I have gotten however, are errors. Firstly, you have an extra ) at line 12:
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
Should be:
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
Lastly, you actually improperly execute your query twice, so the second time, the query is empty. What you have:
$query = mysql_query("INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')");
$result = mysql_query($query) or die('Query failed: ' . mysql_error()));
Should instead be:
$query = "INSERT INTO playerData VALUES ('$name', '$date','$adClick','$playN')";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
Instead of using the insert statement the way you do add the fields that will receive entries explicitly. The database table might have more fields and the insert statement does not explcitly state which fields will receive data.
$query = mysql_query("INSERT INTO playerData (Name,Date,AdClick,PlayN) VALUES ('$name', '$date','$adClick','$playN')");
You have the syntax error on this line
Wrong :
$adClick = mysql_real_escape_string($_GET['adNum]);
Correct :
$adClick = mysql_real_escape_string($_GET['adNum']);

Categories