Can't write to the database using INSERT INTO - php

I have written a form with server side validation using php and now my aim is to insert all the input's from my form into my database (which already has its tables). Below is my syntax:
//Example of one of my validations (for postcode input)
if (empty($_POST["postcode"])) {
$postcodeErr = "";
} else {
$postcode = test_input($_POST["postcode"]);
if(!preg_match("/^[0-9]*$/", $postcode)) {
$postcodeErr = "Only numeric characters";
}
else if (strlen($postcode) != 4) {
$postcodeErr = "Must be 4 digits in length";
}
}
}
//Connect to database server
$conn = mysql_connect("localhost", "-----", "------");
mysql_select_db("-------", $conn)
or die ('Database not found ' . mysql_error() );
// The SQL statement is built
$sql = "INSERT INTO Customer (name, address, suburb, state, postcode)
VALUES ('$_POST[name]', '$_POST[address]', '$_POST[suburb]', '$_POST[$state]', '$_POST[postcode]')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($conn)
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> //end of my php tag
When I run my form, I get a parse error saying that I have an unexpected T_FUNCTION. I know there is a lot above (tried to make it as simple as I can) but I can't seem to word around fixing the error and if I do, I just get another error. Am I writing the code correctly? Normally it's best when other people look at your work. Help will be much appreciated!

The quotes for $_POST['name'] and all other variables was missing in the post variable.
Try with
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$sql = "INSERT INTO Customer (name, Address, suburb, state, postcode)
VALUES ('$name', '$address', '$suburb', '$state', '$postcode')";

you also have one extra brace above database connection, use mysqli prepared statements for better security.
$db = new mysqli('localhost', 'root', '', 'database');
if ($db->connect_errno) {
echo "failed to connect to the database"; die();
}
$name=$_POST['name'];
$address=$_POST['address'];
$suburb=$_POST['suburb'];
$state=$_POST['$state'];
$postcode=$_POST['postcode'];
$stmt = $db->prepare("insert into `Customer` (name, Address, suburb, state, postcode) VALUES (?,?,?,?,?)";
$stmt->bind_param('sssss', $name, $address, $suburb, $state, $postcode);
$stmt->execute();
echo $stmt->affected_rows."record added";

mysql_close($conn) Needs to have a ; after it...
That's why the function after it is unexpected

Agreed with Fred, there seems to be an extra ending brace just above //Connect to database server which is breaking the code.
If that doesn't fix it, please copy/paste your full error message.
EDIT:
else if (strlen($postcode) != 4) {
needs to be
} else if (strlen($postcode) != 4) {
And there are two extra braces at the end of that if statement (just above the //Connect to database server)

Related

query failedERROR: prepared statement "my_query" does not exist

Hello All
I'm trying to insert a form data into my postgreSQL DB in heroku through PHP and i tried all the solutions here but nothing solved my problem!. I can connect to the database but no operation worked well to me!. This error lead me to craziness!.
my code is:
<?php
$db_conn = pg_connect(" host="" port=5432 dbname="" user="" password="" ");
if(!$db_conn){
echo "Error : Unable to connect the database\n";
}
if (isset($_POST['savedata'])) {
$fn = $_POST ['fullname'];
$em = $_POST ['email'];
$ag = $_POST ['age'];
$ge = $_POST ['gender'] ;
$ci = $_POST ['city'] ;
$de = $_POST ['degree'];
$ex = $_POST ['experience'];
$jo = $_POST ['job'];
if($fn != "" and $em != "" and $ag != "" and $ge != "" and $ci != "" and $de != "" and $ex != "" and $jo != "") {
$data1="something to test";
$result = pg_prepare($db_conn, "my_query", "INSERT INTO members (fullname, email, age, gender, city, degree, experience, job) VALUES ($fn, $em, $ag, $ge, $ci, $de, $ex, $jo)");
$result = pg_execute($db_conn, "my_query", array($data1));
if (!$result){
error_reporting(E_ALL);
die("query failed".pg_last_error());
}
else {
echo "<script>";
echo "document.querySelector('.myalert').style.display = 'block';";
echo "setTimeout(function(){
document.querySelector('.myalert').style.display = 'none';
window.location.replace('home');
},5000);";
echo "</script>";
}
}
else {
echo "<script>";
echo "document.querySelector('.myalert1').style.display = 'block';";
echo "setTimeout(function(){
document.querySelector('.myalert1').style.display = 'none';
},2000);";
echo "</script>";
}
}
?>
You have syntax error in your code at the very first line.
Parse error: syntax error, unexpected '" port=5432 dbname="' (T_CONSTANT_ENCAPSED_STRING), expecting ',' or ')
There are also some other issues and oddities so it was just easier to rewrite some parts of your code.
I would also advice you to pay little more attention about the coding style, indentations and etc. It would be significantly easier to read and help you if the code were styled properly. PSR-2 Style Guide would be good place to start.
So here's the rewritten code, but note that I don't have PostgreSQL installed and that's why the code below isn't tested in any way. It should work, but there's also possibility that it doesn't.
See the comments in the code for further explanation.
// Change these credentials according to your needs, but without any quotes
$db_conn = pg_connect("host=localhost port=5432 dbname=mydb user=user password=pwd");
if (!$db_conn) {
die("Error : Unable to connect the database\n");
}
if (isset($_POST['savedata'])) {
$member_details = array(
$_POST['fullname'],
$_POST['email'],
$_POST['age'],
$_POST['gender'],
$_POST['city'],
$_POST['degree'],
$_POST['experience'],
$_POST['job']
);
}
// Iterates through the array and checks if there's any items of which has no proper value
foreach ($member_details as $key => $val) {
if (empty($val)) {
die($key . ' is empty.');
}
}
// Query inside single quotes, also variable names must be $1, $2, $3 etc
$query = 'INSERT INTO members (fullname, email, age, gender, city, degree, experience, job) VALUES ($1, $2, $3, $4, $5, $5, $7, $8)';
$result = pg_prepare($db_conn, "my_query", $query);
$result = pg_execute($db_conn, "my_query", $member_details);
if (!$result) {
// error actions
} else {
// success actions
}

MySQL affected rows -1 when inserting data into database

I want to create a simple piece of code that will put data into the database form a PHP script, everything works fine except putting the data into the database! (I am running a server with PHP7)
The output of the affected rows shows -1 (strange), I double checked my code, compared it with others, tried searching for a common issue on the internet, even tried on a local server with no avail.
You can see it here:
https://leer.bosvision.nl/register.php
My code:
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = 'INSERT INTO users_two (ID, username, password) VALUES (1, gfd, gfd)';
if(mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
To quote the documentation:
-1 indicates that the query returned an error.
And your insert statement indeed errors out, since you don't have a gfd column. If you meant to use that as a value, it should be surrounded by single quotes:
$query = "INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')";
# Here -------------------------------------------------------------^---^--^---^
<?php
$conn = mysqli_connect("localhost", "-user-", "-pass-", "-db-");
if(!$conn) {
$msg = die('connection error');
} else {
$msg = 'Connection success.';
}
echo $msg;
?>
<?php
$query = "INSERT INTO users_two (username, password) VALUES ('gfd', 'gfd')";
if($result= mysqli_query($conn, $query)) {
$result = 'Data saved';
} else {
$result = 'No data saved';
}
$affected = mysqli_affected_rows($conn);
echo $result . '.' . ' Affected rows: ' . $affected;
?>
One assumes ID is auto increment, so that doesn't need to be in there, or is it not and the issue you are encountering is that its a duplicate entry for key. Also you need to wrap your var data in ' '
I would guess that this is an SQL issue. Can you run your query directly on your database? That would give you the error.
Read this page for more info: PHP insert statement
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john#example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Normally you shouldn't be inserting an ID yourself because it should be auto increment.
try adding quotes to the string values, as in:
"INSERT INTO users_two (ID, username, password) VALUES (1, 'gfd', 'gfd')"

Unable to insert data on mysql using php

I am getting error
Undefined variable: company_name.
but some fields are inserted in database.
<?php
$con=mysqli_connect("localhost","root","","vdl");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$Company_name = $_POST['company_name'];
$since = $_POST['since'];
$strength = $_POST['strength'];
$head_quarter = $_POST['head_quarter'];
if($company_name !=''||$since !=''){
mysqli_query($con,"insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
mysqli_close($con);
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
?>
First of all, mysql_* functions are deprecated as of PHP 5.5, and have been completely removed as of PHP 7.0.
Staying up to date with whats new and good now you reguarly want to update things aswell as PHP. Knowing that the mysql_* functions are deprecated (not under active development) we should not use them anymore (we can't even use them anymore if you have updated your php). Anyways back to the point you should not use mysql_* functions especially not now you are new to programming because you will have to update your php someday meaning you will have to change all of your code.
As of the code below:
This is mysqli_* mysqli.php
I have added a check on the db connection checking if that is actually working since you did not check the connection. Because even without that connection working that if loop would still return you your echo.
In mysqli_* you also have to add the connection in the query string.
<?php
$con=mysqli_connect("localhost","root","","vd1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$company_name = $_POST['company_name'];
$since = $_POST['since'];
$strength = $_POST['strength'];
$head_quarter = $_POST['head_quarter'];
if($company_name !=''||$since !=''){
mysqli_query($con,"insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
mysqli_close($con);
}
}
?>
First of all mysql is deprecated. Don't use mysql. Use either mysqli or pdo.
In your given code,
Add condition after $query statement to get exact error.
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
}
else {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
You should trace all errors that may occur. I suggest to use prepared statement, try this:
<?php
$sql = new mysqli("localhost", "root", "", "vdl");
if($sql->connect_errno)
return printf("MySQL Connection Error #%d: %s", $sql->connect_errno, $sql->connect_error);
// I'd recommend to not use $_POST['submit'], it'd be better to check all the fields (company_name, since, strength, head_quarter) using the strlen() function
// for example: if(strlen($company = $_POST["company_name"]) && strlen($since = $_POST["since"])) ... etc.
if(isset($_POST["submit"]))
{
if(!$sm = $sql->prepare("INSERT INTO `digital_library` (`company_name`, `since`, `strength`, `head_quarter`) VALUES (?, ?, ?, ?)"))
return printf("Unable to prepare statement. Error #%d: %s", $sm->errno, $sm->error);
if(!$sm->bind("ssss", $_POST["company_name"], $_POST["since"], $_POST["strength"], $_POST["head_quarter"]))
return printf("Unable to bind parameters. Error #%d: %s", $sm->errno, $sm->error);
if(!$sm->execute())
return printf("MySQL Query Error #%d: %s", $sm->errno, $sm->error);
printf("The query has successfully executed!");
} else
printf("There's nothing to see, get outta here");
?>
If you don't want to use prepared statement, do this:
<?php
$sql = new mysqli("localhost", "root", "", "vdl");
if($sql->connect_errno)
return printf("MySQL Connection Error #%d: %s", $sql->connect_errno, $sql->connect_error);
if(
strlen( $company = $sql->real_escape_string($_POST["company_name"]) )
&& strlen( $since = $sql->real_escape_string($_POST["since"]) )
&& strlen( $strength = $sql->real_escape_string($_POST["strength"]) )
&& strlen( $head_quarter = $sql->real_escape_string($_POST["head_quarter"]) )
) {
$query = sprintf("INSERT INTO `digital_library` (`company_name`, `since`, `strength`, `head_quarter`) VALUES ('%s', '%s', '%s', '%s')", $company, $since, $strength, $head_quarter);
if(!$q = $sql->query($query))
return printf("MySQL Query Error #%d: %s", $sql->errno, $sql->error);
printf("The query has successfully executed!");
} else
printf("There's nothing to see, get outta here");
?>
Do one thing and It will be easy for you to debug-
Change this
$query = mysql_query("insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
to
echo "insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')";
Now when you submit you get the original query in response.
Now run this query in phpmyadmin manually and see the results. Correct the issues phpmyadmin gives you and update your query in your script accordingly.

Why wont my php function insert into database?

So Ive been debugging this for a couple of hours and can't seem to work it out. Ive got a form that takes info into a session then from sessions it goes into a class.
form->session->class->database
Inside the class theres a function that looks like this:
function lagre($kunde)
{
$navn = $kunde->GetNavn();
$telefon = $kunde->GetTelefon();
$epost = $kunde->GetEpost();
$antall = $kunde->GetAntall();
$db = mysqli_connect("localhost","root","","Billett");
if($db->connect_error)
{
die("Couldn't connect");
}
else {
echo "Connected";
}
$sql = "INSERT INTO `Billett`.`Billett` (`BillettID`, `Navn`, `Telefon`, `Epost`, `Antall`) VALUES (NULL, '$navn', '$telefon', '$epost', '$antall')";
$resultat = mysqli_query($db,$sql);
if(!$resultat)
{
echo "<br> Values not inserted";
}
else {
echo "<br> Values inserted";
}
}
The problem is that the values doesn't insert into the database. I cant work out why. Any ideas?
You try to write in different way
$sql = "INSERT INTO `Billett`.`Billett` (`BillettID`, `Navn`, `Telefon`, `Epost`, `Antall`) VALUES (NULL, '".$navn."', '".$telefon."', '".$epost."', '".$antall."')";
Are you using Autocommit? If not then you need to commit your data to the DB, otherwise your INSERT doesn't stick:
/* commit transaction */
if (!$mysqli->commit()) {
print("Transaction commit failed\n");
exit();
}
Example from PHP documentation

MySQL and php connection error

I created a form using php, mysql and xampp server. The problem is that whatever I write in this form it shows that the "message failed to send" and even when I check my db using http://localhost/phpmyadmin/ the message is not there. Here is the code.
P.S I followed a video tutorial and it is exactly the same that made me totally lost. Please help.
The Connection code is:
<?php
$db_host = 'localhost';
$db_user= 'root';
$db_pass= 'the password';
$db_name= 'chat';
if ($connection= mysql_connect($db_host, $db_user, $db_pass)) {
echo "Connected to Database Server...<br />";
if ($database= mysql_select_db($db_name, $connection)) {
echo "Database has been selected... <br />";
} else {
echo "Database was not found. <br />";
}
} else {
echo "Unable to connect to MYSQL server.<br />";
}
?>
And the function code is:
<?php
function get_msg() {
$query = "SELECT 'Sender', 'Message' FROM 'chat' . 'chat'";
$run = mysql_query($query);
$messages= array();
while($message = mysql_fetch_assoc($run)) {
$messages[]= array ('sender' =>$message['Sender'],
'message'=>$message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)){
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO 'chat'.'chat' VALUES (null, '{$sender}', '$message')";
if($run = mysql_query($query)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
?>
I have found the problem in your SQL query:
$query = "INSERT INTO 'chat'.'chat' VALUES (null, '{$sender}', '$message')";
You have to specify the fields there, the SQL query is invalid. Also you have used the wrong escape characters. This works:
$query = "INSERT INTO `chat`.`chat` (`ID`, `sender`, `message`) VALUES (null, '{$sender}', '$message')";
You do not have to specify a null value if you use AUTO_INCREMENT:
$query = "INSERT INTO `chat`.`chat` (`sender`, `message`) VALUES ('{$sender}', '$message')";
And please use MySQLi instead of MySQL because it is deprecated. Furthermore, the database should not be specified twice, simple use:
$query = "INSERT INTO `chat` (`sender`, `message`) VALUES ('{$sender}', '$message')";
$query = "INSERT INTO `chat`.`chat` VALUES (null, '{$sender}', '$message')";
Note the ` and it's not '
I am a novice in PHP and MySQL so I tend to always explicitly exit or die on MySQL on errors.
<?php
$db = new mysqli('host', 'username', 'password', 'db');
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
// no reason to continue, no db connection
}
$statement="SELECT * from `bufferlines` WHERE `beloeb` >'-400' AND `tekst` LIKE 'Dankort-nota SuperB%'";
if(!$res=$db->query($statement)){
printf("Error: %s\n", $db->error); //show MySQL error
echo "<br />".$statement; // show the statement that caused that error
exit("Error 4");//no reason to continue, show where in code
}
?>
This way I get it thrown in my face and cannot get any further until I have pinned down and corrected the error.
The number in exit("Error 4") is only to find the place in the code where it went wrong and thus is unique.
I know this is counter productive when you know your stuff, but for me it's an invaluable learning tool together with php.net dev.mysql.com and stackoverflow.com

Categories