Anyone know why this MYSQL INSERT doesn't work? - php

$con = mysql_connect("localhost","root","");
if (!$con) die('Could not connect: ' . mysql_error());
mysql_select_db("pilot", $con);
$sql = "INSERT INTO logs (id, userid, date, plane, from, to, blocksoff, takeoff,
landing, blockson, flighttime, traveltime, tachobefore, tachoafter, tacho,
hobbsbefore, hobbsafter, hobbs, landings) VALUES ('$nfid', '$nfuserid',
'$nfdate', '$nfplane', '$nffrom', '$nfto', '$nfblocksoff', '$nftakeoff',
'$nflanding', '$nfblockson', '$nfflighttime', '$nftraveltime', '$nftachobefore',
'$nftachoafter', '$nftacho', '$nfhobbsbefore', '$nfhobbsafter', '$nfhobbs',
'$nflandings')";
mysql_query($sql);
there ain't nothing wrong with the $sql, it seems like it just wont query.. :(
id|userid=int(11)
date=date
plane|from|to=text
blocksoff|takeoff|landing|blockson=time
flighttime|traveltime|tachobefore|tachoafter|tacho|hobbsbefore|hobbsafter|hobbs|landings=double
all of the $ variables come from a textbox (if it matters)

May be some of the column names are MySql reserved words (especially from and to). Please escape them.
INSERT INTO logs (`id`, userid, date, plane, `from`, `to` ...)

You should always be checking for errors:
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}

Kind of an open ended question....
Are any of your variables returning NULL values? If you are trying to insert NULL into the database, and the database column isn't set to accept NULL values, that could be causing an error.
You need to see what the query is actually doing. If you have any single quotes or other invalid character from the textbox, that could be screwing you up.
Also, for your own personal improvement, look up PDO. It helps you write much more secure queries through the use of prepared statements.
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

Related

mysql INSERT INTO query - ERROR with syntax

Can anyone help with advising what may be wrong with my insert into syntax please ?
Working except i am receiving empty query message
// values sent from form
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$postcode=$_POST['postcode'];
$gender=$_POST['gender'];
$yob=$_POST['yob'];
/*********** CONNECT TO THE DATABASE ******/
//Step 1 CONNECT TO THE DATABASE
$db=mysql_connect ("localhost", “db_username, “db_password);
if (!$db) {
die("Database connection failed miserably: " . mysql_error());
}
//Step2 SELECT THE DATABASE
$db_select = mysql_select_db(“db_name,$db);
if (!$db_select) {
die("Database selection also failed miserably: " . mysql_error());
}
echo "Welcome $first_name!";
echo " Success, connected to database but maybe not the table";
// Insert data into database
//##############################I THINK PROBLEM MUST BE HERE IN THIS INSERT STATEMENT STATEMENT###################################
$sql="INSERT INTO newsletter-subscribers(first_name, last_name, email, postcode, gender, yob)VALUES('$first_name','$last_name','$email','$postcode','$gender','$yob')";
if(mysql_query($sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysql_error($db);
}
$result=mysql_query($sql);
Your query,
$sql="INSERT INTO newsletter-subscribers(first_name, last_name, email, postcode, gender, yob)VALUES('$first_name','$last_name','$email','$postcode','$gender','$yob')";
Your new query,
$sql = "INSERT INTO `newsletter-subscribers` (first_name, last_name, email, postcode, gender, yob) VALUES ('$first_name','$last_name','$email','$postcode','$gender','$yob')";
So, what has changed?
Added ticks around your table name.
Removed spaces which you didn't need to make query clearer.
Without the backticks around your table name, MySQL is treating it as newsletter minus subscribers. Which is wrong, add the ticks to tell MySQL that it is a table name.
Edit 1
This might be a copy & paste error, I'm not sure, however...
Your db connect is incorrect too, you aren't assigning any values to it as your quotes are not closed and are smart quotes.
Your connect,
$db = mysql_connect ("localhost", “db_username, “db_password);
Your new connect,
$db = mysql_connect("localhost", "db_username"," db_password");
Also,
$db_select = mysql_select_db(“db_name,$db);
To,
$db_select = mysql_select_db("db_name", $db);
Notice the difference in the quotes.
Edit 2
Your code is prone to SQL injection, you are still using MySQL even though it has been deprecated, you should use either MySQLi or PDO with prepared statements.
Not to mention your $_POST data is being passed on to the query without being sanitized, you should start using htmlspecialchars it would make it better and prevent XSS.
Your table name contains a dash, so you need to quote it. The backtick or back-quote character is used to quote symbol names in MySQL (such as the names of tables, columns, etc), so you would need something like this:
INSERT INTO `newsletter-subscribers` (first_name, ...

mysql_insert_id() not returning a value -

I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.
The insert works too.
My table is as follows:
idint(9) NOT NULL auto_increment,
and id is set as primary
What am I doing wrong?
$conn = mysql_connect($host,$username,$password);
mysql_select_db($database, $conn) or die( "Unable to select database");
include "update_activity.php";
updateActivity("logged in", "On Break");
$date = date("m/d/y"); $starttime = time();
$sesh = $_SESSION['fname']." ".$_SESSION['lname'];
$q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";
$query = mysql_query($q, $conn);
$id = mysql_insert_id($conn);
echo var_dump($id); exit;
edited to show my more recent attempts
Have read all comments given and your replies to each.
Only one of these is possible:
Either the query works properly OR
You are not getting the generated primary key.
Both of these can never be true.
Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?
To diagnose the problem, we have to go though the normal way.
Dump your generated query before calling mysql_query.
Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.
error_reporting(E_ALL);
ini_set('display_errors','on');
echo "before calling: $q\n";
$query = mysql_query($q, $conn);
if(!$query)
{
echo "Error:" . mysql_error($conn);
return;
}
echo " generated id:" . mysql_insert_id($conn);
#adelphia as far as i get the idea there is a problem in the query that is executed.
plz check the query properly
Borrow a lead from this code extracted from here:
http://php.net/manual/en/function.mysql-insert-id.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
The problem with your insert query
$q = "INSERT INTO `breaks` (date, starttime, user)
VALUES ('".$date."',
'".$starttime."',
'".$_SESSION['fname'] $_SESSION['lname']."')";
try with this
and main thing you are using most of the deprecated "mysql" things like "mysql_insert_id()"
store the values that u want to pass into an array or variable and pass it in the insert query.
its should work fine then...

php query to insert string into database

<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username&&$password)
{
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database");
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
$result = mysql_query($query) or die("Error occurred.");
}
else die("Please enter a username and password.");
?>
For this part of the code:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The VALUES seem to not be working properly, I need whatever the string value of $username is to be inserted into my CiniUsers database. What do I need to do to make the code above work? I'm very new to php and sql syntax and the guides I'm finding online are all completely different from each other as if they keep updating php.
Try reviewing this part:
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('$username')";
The syntax is:
$query = "INSERT INTO table (column) VALUES ('$strvar')";
What is the column name you wanted to insert into?
If it is username.CINIDAT then try removing the qoutes.
Like this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
or maybe your column is named username so:
$query = "INSERT INTO CiniUsers (username) VALUES ('$username')";
UPDATE
The query from your comment, change it to this:
$query = "INSERT INTO CiniUsers (username.CINIDAT) VALUES ('$username')";
The format for the SQL statement is as so:
INSERT INTO nameOfTable (column1, column2, column3, etc) VALUES ('column1', 'column2', 'column3', 'etc')
You MUST make sure that you are using the field names exactly as they are stored in MySQL.
Your SQL could appear like so:
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
OR
$query = "INSERT INTO CiniUsers (username) VALUES('{$username}')";
Another thing that may help is that your die() statement is not very helpful. Yes, it is a bummer when your php program quits early, but it will save you a lot of time and frustration if you know why it quit. Although you may still be learning PHP and MySQL and may not know what the errors mean, they will start to make sense the more you see them and can tell you whether your query was bad, the connection failed or many more things. Change to something like this:
$connect = mysql_connect("CiniCraftData.db.55555555.hostedresource.com", "CiniCraftData", "*********") or die("Couldn't Connect: mysql_error()");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database: mysql_error()");
...
$result = mysql_query($query) or die("Some kind of error occurred...Query failed: mysql_error()");
You find that seeing the mysql_error() will help you solve problems like this much faster.
USE phpMyAdmin to test your query out, your query may be working perfectly. It is really the only way to know for sure. Use the suggested SQL and replace the PHP variable with some dummy data like "testUsername_1". If the query works, you will have manually added the username to the db, if not, the problem lies in SQL statement.
Here is some documentation on SQL INSERT INTO statements if you need more details:
http://www.w3schools.com/sql/sql_insert.asp
I think you should use mysqli or pdo. This liberary you are using is deprecated.
That said, what is username.CINIDAT? I think this is where your problem is. It should be something like this
$query = "INSERT INTO CiniUsers (username) VALUES('$username')";
I am assuming that CiniUsers is the table name and username is the column name.
The simplest way is to build the query by concatenating the statement with the value.
$query = "INSERT INTO CiniUsers ('username.CINIDAT') VALUES('".$username."')";
Without validation, this is not a very good idea, or something like this is very easy.

mySQL query syntax error?

I have contact form at my wordpress site which is delivered by ajax, and sent to my mail. I also wanted to save the results in a database so I wrote this query, but it gives me and syntax error, but I can't find anything wrong in this code:
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("u31272B3", $con);
$sql="INSERT INTO wp_contactform (Nimi, Puhelin, E-mail, Viesti, IP, Day)
VALUES
('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
The jquery script that sends it works, and the mail is sent, but this doesn't save.
Quote the column name E-mail with backticks (`). MySQL is interpreting this in two parts at the moment.
Note also, (as per my comment) that your code is wide open to SQL injection attacks. It is much better to use properly parameterised SQL queries.
SQL injection example:
"INSERT INTO table (field) VALUE ('$_POST[var]')"
If you post the value "'; DROP TABLE table; --" then you have a valid SQL string that inserts an empty string, then attempts to drop the table. Substitute whatever harmful statement you want.
and also you should use mysql_real_escape_string() or prepared statements. if your query data have any special characters it can blow your query it also help you from sql injection too.
http://php.net/mysql_real_escape_string
http://php.net/pdo
Your SQL request should be written as below:
$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
VALUES
('$_POST[Nimi]','$_POST[Puhelin]','$_POST[Sposti]','$_POST[Tiedot]','$_POST[Gotcha]','$_POST[Day]')"
SQL fields using non-alphanumeric characters have to be escaped with backticks (`)
This should work
<?php
$con = mysql_connect("localhost", "username", "password");
if(!$con){
die('Could not connect: '.mysql_error());
}
mysql_select_db("u31272B3", $con);
$sql = "INSERT INTO wp_contactform (`Nimi`, `Puhelin`, `E-mail`, `Viesti`, `IP`, `Day`)
VALUES
('".mysql_real_escape_string($_POST['Nimi'])."','".
mysql_real_escape_string($_POST['Puhelin'])."','".
mysql_real_escape_string($_POST['Sposti'])."','".
mysql_real_escape_string($_POST['Tiedot'])."','".
mysql_real_escape_string($_POST['Gotcha'])."','".
mysql_real_escape_string($_POST['Day'])."')";
if(!mysql_query($sql, $con)){
die('Error: '.mysql_error());
}
echo "1 record added";
mysql_close($con);

INSERT INTO database table, from form not working. SQL

lets get straight to my problem, the code I have written here does not write to my database and I cannot figue out why. At the moment I am simply trying to get to grips with php and sql so there is no point to this form other than learning. Here is the error i am getting(the first sentence 'connected to database' is from my if statement):
"Connected to databaseError: 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 ''test' ('name') VALUES ('daniel')' at line 1"
The code I have may look a little confusing as some of it is from w3schools and some is from a friend. I cannot figure out why this code isn't working, I have tried many variations of the syntax based on loads of articles I have found online and on stackoverflow but none seem to work. I fear that maybe I am not even connectec to the database, although my if statement tells me otherwise, so that could be a problem?
Hopefully if this gets solved this question will clarify database connection and writing to a database from a form in one hit. Thanks in advance guys and here's my code.
HTML
<form action="insert.php" method="post">
Name: <input type="text" name="namefield" />
<input type="submit" />
</form>
PHP (insert.php)
<?php
$dbhost = 'localhost';
$dbname = 'carbon_db';
$dbuser = 'username';
$dbpass = 'password';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if($con == FALSE)
{
echo 'Cannot connect to database' . mysql_error();
}
else
{
echo 'Connected to database';
}
mysql_select_db($dbname, $con);
$sql="INSERT INTO 'test' ('name')
VALUES ('$_POST[namefield]')";
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Drop the quotes around the table name or change them to back ticks:
Change:
$sql="INSERT INTO 'test' ('name') VALUES ('$_POST[namefield]')";
To:
$sql="INSERT INTO test ('name') VALUES ('$_POST[namefield]')";
Or
$sql="INSERT INTO `test` ('name') VALUES ('$_POST[namefield]')";
It's often best to use backticks for MySQL as like any other storage engines it has it's own reserved names and it's own reserved insert practices.
try with
$sql = "INSERT INTO `test` (`name`) VALUES ('".$_POST['namefield']."')";
Change the single quotes surrounding the table name and the column name to backticks. Or get rid of them all together.
$sql="INSERT INTO `test` (`name`) VALUES ('{$_POST['namefield']}')";
Also, don't reference associative arrays ($_POST) directly in a string without using {} syntax or breaking up the string - what you have done there issues an E_NOTICE and should be avoided.
Read this thoroughly - you'd be amazed what you can (and can't) legally do in PHP strings...
try using ` instead of ' when refering to table/column names
$sql="INSERT INTO `test` (`name`)
VALUES ('$_POST[namefield]')";
Remove the single quotes around your sql statement and replace with back-tics (not sure even they are necessary):
$sql="INSERT INTO `test` ('name')
VALUES ('$_POST[namefield]')";

Categories