php inserting to database fail - php

I have following message box error, says Failed. these are my codes:
<?php
require('admin/connectdb.php');
if (isset($_POST['Sub']))
{
//get data from reservation form
$cutomername=$_POST['aname'];
$gender=$_POST['sex'];
$phoneno=$_POST['tel'];
$email=$_POST['email'];
$age=$_POST['age'];
$computerpart=$_POST['partcomp'];
$option1=$_POST['option1'];
$notes=$_POST['Notes'];
$query="INSERT INTO `assignmentwebprog`.`reservation` (`cumstomername`, `gender`, `phoneno`, `email`, `age`, `typeofcomputerpart`, `option`, `notes`)
VALUES ('$cutomername', '$gender', '$phoneno', '$email', '$age', '$computerpart', '$option1', '$notes')";
$qresult = mysql_query($query);
if ($qresult){
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
}
else
{
echo "<script type='text/javascript'>alert('failed!')</script>";
}
}
?>
up there is inserting value to phpmyadmin & every time i load/input then click enter then the page shows message box "failed"
these are my database:
<?php
$host="localhost"; // Host name
$username="root"; // username
$username="root"; // username
$db_name="assignmentwebprog"; //database name
$tbl_name="reservation";
// Replace database connect functions depending on database you are using.
mysql_connect("$host", "$username", "$password");
mysql_select_db("$db_name");
?>
currently my database is phpmyadmin, is there something missing with my code?

Check to see if the field in the database cumstomername is spelt correctly.
It should probably be customername
Passing the paramter
$cutomername=$_POST['aname'];
SQL
$query="INSERT INTO `assignmentwebprog`.`reservation` (`cumstomername`, `gender`, `phoneno`, `email`, `age`, `typeofcomputerpart`, `option`, `notes`)
VALUES ('$cutomername', '$gender', '$phoneno', '$email', '$age', '$computerpart', '$option1', '$notes')";

Change this line and try:
$qresult = mysql_query($query) or die(mysql_error());

check this :
$query="INSERT INTO reservation (cumstomername, gender, phoneno, email, age, typeofcomputerpart, option, notes)
VALUES ('$cutomername', '$gender', '$phoneno', '$email', '$age', '$computerpart', '$option1', '$notes')";
$qresult = mysql_query($query) or die(mysql_error());

You might have missing something in the $query which is mandatory for the table insertion.
First echo the query on the page. // echo $query ;
Then RUN the query in phpmyadmin and you will get the reason why it is not inserting in the table. See the error there.

Related

Db Insert from php form not working

I have put together what I think is a simple addition to a php form-processing script (to insert data in a database, after sending it through to an email).
For some reason, I always get the error message, and the actual input of the data never gets through to the database. I've added the query to the output, and all the received values seem alright.
Thanks in advance.
// username, passw, database are all defined earlier in code.
// all the variables are taken out of form inputs (and they all arrive fine by email.
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
//inserting data order
$order = "INSERT INTO flights('restime', 'flyfrom', 'flyto', 'dateoutbound', 'outboundflex', 'datereturn', 'returnflex', 'pax', 'klasse', 'name', 'email', 'phone', 'comments', 'status') VALUES('$date', '$fly_from', '$fly_to', '$date_outbound', '$outbound_flex', '$date_return', '$return_flex', '$pax', '$class', '$name', '$email', '$phone', '$comments', '1')";
//declare in the order variable
$result = mysql_query($order); //order executes
if($result){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
echo $order;
}
Thanks a lot in advance.
Database configuration setting must be like below
$link=mysql_connect(localhost,$username,$password);
#mysql_select_db($database,$link) or die( "Unable to select database");
After this you can write your insert query and etc....
You should not use the single quotes for fields in the query. if you use the backticks, then you don't get error. Just like the following
You must use the mysql_error() function to check the error in the query. Check the below code.
I have found one more issue. You have to use single quotes around the hostname in mysql_connect function. This also may cause error.
I have used the following code. It is working fine for me.
<?php mysql_connect('localhost','root','');
#mysql_select_db('test') or die( "Unable to select database");
//inserting data order
$order = "INSERT INTO testone (`restime`, `flyfrom`, `flyto`, `dateoutbound`, `outboundflex`, `datereturn`, `returnflex`, `pax`, `klasse`, `name`, `email`, `phone`, `comments`, `status`) VALUES('$date', '$fly_from', '$fly_to', '$date_outbound', '$outbound_flex', '$date_return', '$return_flex', '$pax', '$class', '$name', '$email', '$phone', '$comments', '1')";
//declare in the order variable
$result = mysql_query($order) or die(mysql_error()); //order executes
if($result){
echo("<br>Input data is succeed");
} else{
echo("<br>Input data is fail");
echo $order;
}
error is in this query :
$order = "INSERT INTO flights('restime', 'flyfrom', 'flyto', 'dateoutbound', 'outboundflex', 'datereturn', 'returnflex', 'pax', 'klasse', 'name', 'email', 'phone', 'comments', 'status') VALUES('$date', '$fly_from', '$fly_to', '$date_outbound', '$outbound_flex', '$date_return', '$return_flex', '$pax', '$class', '$name', '$email', '$phone', '$comments', '1')";
You are using ' in-spite of using ` for the column name in the table.
use this query and i am sure it will run great
$order = "INSERT INTO testone (`restime`, `flyfrom`, `flyto`, `dateoutbound`, `outboundflex`, `datereturn`, `returnflex`, `pax`, `klasse`, `name`, `email`, `phone`, `comments`, `status`) VALUES('$date', '$fly_from', '$fly_to', '$date_outbound', '$outbound_flex', '$date_return', '$return_flex', '$pax', '$class', '$name', '$email', '$phone', '$comments', '1')";
:)

mySQL insert wont update database

I have a form that sends data to the php below. No errors appear but no information is inserted into the database and I don't understand why. I have triple checked all the table names etc and everything is correct. The code echo's out what I put into the form but it doesn't update to the database!
<?php
//variables for db
$username = "";
$password = "";
$hostname = "localhost";
$dbname = "infinity";
//connection to the database
$con = mysql_connect($hostname, $username, $password);
if($con == FALSE)
{
echo 'Cannot connect to database' . mysql_error();
}
mysql_select_db($dbname, $con);
$name=$_POST["name"];
$logo=$_POST["logo"];
$logo="<img src=\"images/".$logo."\" alt=\"$name Logo\" />";
$blurb=$_POST["blurb"];
$link=$_POST["link"];
echo $name;
echo $logo;
echo $blurb;
echo $link;
//Insert Values into Database
mysql_query("INSERT INTO `infinity`.`sponsors` (`name`, `logo`, `blurb`, `link`) VALUES ('$name', '$logo', '$blurb', '$link');");
?>
Try to get an error message of you query:
mysql_query($your_query) OR die(mysql_error());
try this
mysql_query("INSERT INTO `infinity`.`sponsors` (`name`, `logo`, `blurb`, `link`)
VALUES ('$name', '$logo', '$blurb', '$link')") or die(mysql_error());
else you make check it.
$sql ="INSERT INTO `infinity`.`sponsors` (`name`, `logo`, `blurb`, `link`)
VALUES ('$name', '$logo', '$blurb', '$link')";
$sqlinset= mysql_query($sql) or die(mysql_error());
echo $sql;
echo $sqlinset;
Try this:
mysql_query("INSERT INTO `infinity`.`sponsors` (`name`, `logo`, `blurb`, `link`) VALUES ('$name', '$logo', '$blurb', '$link');", $con);
And be sure to secure those variables you put in your database from SQL ijection and XSS attacks.

PHP Mysql Query (INSERT) Issue

I am having an issue with a MySQL query as follows:
My script generates this as an example query:
INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('Test2', '123-456-7890', 'test#test.com', 'mesa', 'az', '04-14-2013')
Which if I drop directly into PHPMyA, works fine. However, the PHP script I am trying to use to send the query from my website is not working and I can't get it figured out. Here it is:
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
mysql_query($sql);
$result = mysql_query($sql);
if($result)
{
echo("<br>Data Input OK");
}
else
{
echo("<br>Data Input Failed");
}
Nothing makes it to the MySQL DB and no PHP errors are displayed, however, if I echo $sql I get the exact query I posted previously.
Just remove the single line mysql_query($sql); on your code and you will be fine.. But you should better start practicing PHP MySQLi which stands for PHP MySQL Improved, such:
$con = mysqli_connect($host, $user, $password, $password);
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
$result = mysqli_query($con, $sql);
if($result) {
echo("<br>Data Input OK");
} else {
echo("<br>Data Input Failed");
}
$sql = 'INSERT INTO Table_name (`id`, `name`) VALUES ("1", "php");
You are executing $sql twice in your script wich is causing the error, please remove
mysql_query($sql);
And it will be ready to go
I would also suggest to stop using mysql_query please switch to mysqli or PDO
Are you sure there is a valid connection (..mysql_connect())? Try using the full syntax like so..
$conn = mysql_connect(...);
$result = mysql_query($query, $conn);
Also try forcing a commit after you execute the statement -
$mysql_query("COMMIT", $conn);
You are running mysql_query twice. Reason of the error. Try running the following code.
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
$result = mysql_query($sql) or die(mysql_error());
if($result){
echo("<br>Data Input OK");
} else{
echo("<br>Data Input Failed");
}
use this
"INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$_POST[name]', '$_POST[phone]', '$_POST[email]', '$_POST[city]', '$_POST[state]', '$_POST[date]')";
Try to use mysql_query($sql,$con); instead of mysql_query($sql);.
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$age=$_POST['age'];
$address=$_POST['address'];
$ins="insert into table_name(`name`,`age`,`address`)values('".$name."','".$age."','".$address."')";
mysql_query($ins);
echo 'data inserted successfully';
}

Mysql Insert Into Error

I've created a registration form and I'm adding the data with php but for some reason it will not let me add the data into the database. Can you see anything wrong with this code?
<?php
mysql_connect("localhost", "root", "password") or die("No Connection");;
mysql_select_db("music") or die("No Database");;
$username= mysql_real_escape_string($_REQUEST["username"]);
$password= mysql_real_escape_string($_REQUEST["password"]);
$email= mysql_real_escape_string($_REQUEST["email"]);
$hash = md5( rand(0,1000) );
mysql_query("INSERT INTO members (id, username, password, email, hash, active) VALUES('', '$username', '$password', '$email', '$hash', '')") or die("Can't Add");
if(mysql_affected_rows()>0){
echo "1";
}else{
echo "2";
}
?>
I Keep getting a Can't Add error indicating that there is a simple problem with the mysql_query row
Thank you
Can't add is not an error, just a catch all statement you added at the end.
To see your actual problem, change your code at the end of the mysql_query line to include the actual error retrieved from mysql_error().
mysql_query("INSERT INTO members (username, password, email, hash, active) VALUES('$username', '$password', '$email', '$hash', '')")
or die("Can't Add - " . mysql_error());
That will give you more details regarding the error, if you post that, I can update my answer with the reason why.
Note that I've also removed the insertion of id, it's not needed if your column is AUTO_INCREMENT, which it should be.
if id is your primary key then replane '' with null
Make id as auto-incremented primary key and remove it from insert query.
there may be unique constraints for any of the column
Either have
mysql_query("INSERT INTO members (id, username, password, email, hash, active)
VALUES(null, '$username', '$password', '$email', '$hash', '')") or die("Can't Add");
^^^^
OR
mysql_query("INSERT INTO members (username, password, email, hash, active)
VALUES( '$username', '$password', '$email', '$hash', '')") or die("Can't Add");

mysqli insert doesnt work, no error message, connection successful

I'm noobish to coding. I set up a MYSQL database called contacts, a table called contactstable with fields id, firstname, lastname, emailaddress,postalcode and phonenumber. Each are text or varchars except for the id, which is an auto_increment, pk field. The connection doesnt give any errors, and no error is relayed through the mysqli_connect_error() method. They query doesnt go through and no query is executed. I cant figure out why.
<html>
<head>
<title>Registration</title>
</head>
<body>
<h1>Register with Us!</h1>
<h2>Registration Complete!</h2>
<div class="feedback-container" <?= isset($_REQUEST["first-name"])? "style=\"display:block\"": "style=\"display:none\""; ?>>
<?php
$firstname = $lastname = $emailaddress = $postalcode = $phonenumber = NULL;
if (isset($_REQUEST["first-name"])){
$firstname = $_REQUEST["first-name"];
$lastname = $_REQUEST["last-name"];
$emailaddress = $_REQUEST["email-address"];
$postalcode = $_REQUEST["postal-code"];
$phonenumber = $_REQUEST["phone-number"];
$dbconn = new mysqli();
$dbconn->connect("localhost","root","","contacts");
if(mysqli_connect_error()){
echo "Connection Failed";
}else{
echo "Connection Established";
}
$query = "INSERT INTO 'contactstable' ('firstname', 'lastname', 'emailaddress','postalcode','phonenumber') VALUES ('$firstname', '$lastname', '$emailaddress', '$postalcode', '$phonenumber')";
if ($dbconn->query($query) == TRUE){
echo ("Thank you for registering with us. We will shortly send a confirmation email to $emailaddress.");
}else{
echo ("<p>Your contact information was not added to our database. Please try again later or contact our webadmin at webadmin#gmail.com</p>");
}
}
?>
</div>
</body>
When it runs, it outputs the following:
"Connection Established"
"Your contact information was not added to our database. Please try again later or contact our webadmin at webadmin#gmail.com"
There are no error messages.
There is no data updated.
I'd make this
$query = "INSERT INTO 'contactstable' ('firstname', 'lastname', 'emailaddress','postalcode','phonenumber') VALUES ('$firstname', '$lastname', '$emailaddress', '$postalcode', '$phonenumber')";
look like this
$query = "INSERT INTO contactstable (firstname, lastname, emailaddress,postalcode,phonenumber) VALUES ('$firstname', '$lastname', '$emailaddress', '$postalcode', '$phonenumber')";
query should look like this.
INSERT INTO `contactstable`
(`firstname`, `lastname`, `emailaddress`,`postalcode`,`phonenumber`)
VALUES
('$firstname', '$lastname', '$emailaddress', '$postalcode', '$phonenumber')
Use backticks if you want to quote your field names.
$query = "INSERT INTO `contactstable` (`firstname`, `lastname`, `emailaddress`,`postalcode`,`phonenumber`) VALUES ('$firstname', '$lastname', '$emailaddress', '$postalcode', '$phonenumber')";
Also you can use " if you set SET sql_mode='ANSI_QUOTES'
http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html

Categories