Why wont this MySQL Query save - php

So I have this short script. Its not giving out any error but it will not save into the DB. After I run the script I check the DB and nothing is there.
The db only has two items. (id and fid) ID is set at INT 11 auto and fid is set at VARCHAR 64. Also, I am connecting to my DB just fine.
<?php
$con = mysqli_connect('####', '####', '####', '#####');
if (mysqli_connect_errno()) {
echo 'Failed to Connect to MySQL' . mysqli_connect_errno();
}
if (isset($_POST['submit'])) {
$fid = $_POST['fid'];
$query = mysqli_query($con, "SELECT * FROM fid where fid = '$fid'");
$row = mysqli_num_rows($query);
if ($row == 1) {
echo 'This Federal Tax ID is already in use.';
} else {
mysqli_query($con, "INSERT INTO `fid` (id, fid) VALUES ('', '$fid')");
}
}
?>

Based on your comment:
It's supposed to be an empty value so the ID auto increments everytime.
That's not how auto-increment works. Your code is explicitly telling the record to not have a value:
"INSERT INTO `fid` (id, fid) VALUES ('', '$fid')"
If the id column is required, this will expectedly fail. (It may also be failing based on the type. You're trying to insert a string, but an auto-increment column would be numeric...)
An auto-increment column doesn't need to be supplied an empty value. Just omit it entirely:
"INSERT INTO `fid` (fid) VALUES ('$fid')"
Additionally, this code is wide open to SQL injection. You're going to want to read up on that. In short, you should use prepared statements which bind to user-input values. Don't concatenate those user-input values directly into your code, that allows the user to inject their own code.

If you want to use AUTO you need to either NOT specify the value at all or else specify a 0 (or NULL if defined as NOT NULL):
Either
INSERT INTO fid (fid) VALUES ('$fid')
or
INSERT INTO fid (id, fid) VALUES (0, '$fid')
or (if id is defined as NOT NULL)
INSERT INTO fid (id, fid) VALUES (NULL, '$fid')
SOURCE: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Related

ON DUPLICATE KEY query - pulling out the primary key of a table

I have a query which I would like to INSERT some data into my table however, if there is already data inside of a particular field checkPoint, then run an UPDATE. After a lot of research on here, users have suggested using ON DUPLICATE KEY.
This query works however as apposed to updating an already existing row, it inserts a new one, with a new primary key, please can someone explain where I have gone wrong, or what I've missed out.
<?php
$idUsers = $_SESSION['id'];
$ModuleID = 5;
$checkPoint = 999;
$query= "INSERT INTO `userTakingModule` (`userTakingModuleID`, `idUsers`, `ModuleID`, `checkPoint`) VALUES (NULL, $idUsers, $ModuleID, $checkPoint) ON DUPLICATE KEY UPDATE `idUsers` = VALUES ($idUsers), `ModuleID` = VALUES ($ModuleID), `checkPoint` = VALUES ($checkPoint) ";
$result = $conn -> query($query);
?>
Screenshot of my database layout: the table called userTakingModule in the middle is where the query is applied to.
This is what is happening at the moment as I need to include the Primary Key of userTakingModuleID into the query somehow. (I almost need to say, look for where there is an already existing entry of the same idUser and ModuleID?)
The important part of using INSERT...ON DUPLICATE KEY UPDATE is telling MySQL what the key is, so it can look for duplicates. You said:
I almost need to say, look for where there is an already existing entry of the same idUser and ModuleID
And that's exactly right. You need to create a UNIQUE index on those two columns like so:
ALTER TABLE userTakingModule ADD UNIQUE INDEX(idUser, ModuleID);
Now, conflicts will trigger the update functionality. You should just remove the userTakingModuleID column from your query altogether, it will be given a value automatically as needed. You're also mis-using the VALUES function; you should pass it a column name, and it will resolve to the value that would have been inserted into that column without a conflict. So you can use either the VALUES function, or the variable itself.
And speaking of variables, I would be remiss if I didn't point out how insecure and dangerous it is to insert variables directly into queries. You should always use prepared statements. You don't provide enough code to know which database API you're using, but for PDO it would look like this:
$idUsers = $_SESSION['id'];
$ModuleID = 5;
$checkPoint = 999;
$query= "INSERT INTO userTakingModule (idUsers, ModuleID, checkPoint) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE idUsers = VALUES (idUsers), ModuleID = VALUES (ModuleID), checkPoint = VALUES (checkPoint)";
$stmt = $conn->prepare($query);
$stmt->execute([$idUsers, $ModuleID, $checkPoint]);
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
And for mysqli something like this (though I'm not too familiar with it)
$idUsers = $_SESSION['id'];
$ModuleID = 5;
$checkPoint = 999;
$query= "INSERT INTO userTakingModule (idUsers, ModuleID, checkPoint) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE idUsers = VALUES (idUsers), ModuleID = VALUES (ModuleID), checkPoint = VALUES (checkPoint)";
$stmt = $conn->prepare($query);
$stmt->bind_param("iii", $idUsers, $ModuleID, $checkPoint);
$stmt->execute();
$result = $stmt->get_result();

Stuck at this error: Incorrect integer value: '' for column '____' at row 1

When I submit the form and use this script to insert the data in the db i get the error mentioned above...any ideas?
//Include connect file to make a connection to test_cars database
include("prototypeconnect.php");
$proCode = $_POST["code"];
$proDescr = $_POST["description"];
$proManu = $_POST["manufacturer"];
$proCPU = $_POST["cost_per_unit"];
$proWPU = $_POST["weight_per_unit"];
$proBarCode = $_POST["bar_code"];
$proIngredients = $_POST["ingredients_list"];
$proAllergens = $_POST["allergens_contains"];
$proMayAllergens = $_POST["allergens_may_contain"];
//Insert users data in database
$sql = "INSERT INTO prodb.simplex_list
code, description, manufacturer,
cost_per_unit, weight_per_unit, bar_code,
ingredients_list, allergens_contains,
allergens_may_contain)
VALUES
( '$proCode', '$proDescr' , '$proManu',
'$proCPU' , '$proWPU' , '$proBarCode',
'$proIngredients' , '$proAllergens',
'$proMayAllergens')";
//Run the insert query
if (!mysql_query($sql)) {
echo mysql_error();
}
?>
UPDATE: I removed id inserts as they are auto-increment and i learned from your answers that a null does not need to be coded and mysql looks after AI. Thanks guys!
Query need to be like:-
$sql = "INSERT INTO prodb.simplex_list
(code, description, manufacturer,
cost_per_unit, weight_per_unit,
bar_code, ingredients_list, allergens_contains,
allergens_may_contain)
VALUES ('$proCode', '$proDescr', '$proManu',
'$proCPU','$proWPU', '$proBarCode',
'$proIngredients', '$proAllergens',
'$proMayAllergens')";
Note:- please stop using mysql_*. Use mysqli_* or PDO. Also this will work only when id field must be auto incremented.

PHP MySQL - Am I doing anything wrong?

For two hours now, I'm trying to insert a value into a table. I don't get any error and I can't find out the problem!
The value that I'm trying to insert:
$query = "INSERT INTO banlist (banid, active, ip, by, date, reason) VALUES (NULL, 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')";
mysql_query($query);
An example value that works perfectly:
$query = "INSERT INTO accounts (username, password, email, regdate) VALUES ('test', 'test', 'test#test.test', 't-t-t t:t:t')";
mysql_query($query);
I can't find the problem! Am I missing anything? Both tables exist.
The issue is that the name you've chose for a field "by" is a reserved word. You'll have to update it to a word that's not on this list.
Also, in future you can easily see what's wrong by checking if mysql_query() returned false, and then calling mysql_error() for an error message.
Try this:
CREATE TABLE ban (
banid int auto_increment primary key,
active int,
ip varchar (20),
`by` varchar (20),
`date` varchar(8),
reason varchar(20)
);
INSERT INTO ban (active, ip, `by`, `date`, reason)
VALUES
(1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')
;
SELECT * FROM ban;
http://www.sqlfiddle.com/#!2/1959f/1
Some remarks:
Like several others (e.g. #wintercounter, #user1909426 ) have pointed out you are using restricted words in MySQL. If you do use a restricted word then use `` (back ticks) or just use them on every column.
I think that using a null in your first part of you insert gives a problem. This column is probably an integer column with auto_increment. See #wintercounter answer.
Fortunately date is not a restricted name. B.T.W. you could use use a date value instead of you varchar value now.
With regard to the comments from #tadman using mysql instead of mysqli or PDO is not recommended. The mysql library is depreciated from version PHP 5.5 onwards, see the php manual. You will also need to include error handling.
For completeness sake, this is the php code when using MySQLi:
$link = mysqli_connect($hostname, $username, $password, $database);
if (!$link){
echo('Unable to connect to database');
}
else{
mysqli_query("INSERT INTO ban (active, ip, `by`, `date`, reason) VALUES (1,'10.25.47.88', 'AUTOBAN', '12-12-45', 'test'))", $link);
}
mysqli_close($link);
For mysql version:
$hostname = "hostname";
$username = "username";
$username = "password";
$database = "database";
$link = mysql_connect($hostname, $username, $password);
mysql_database ($database)
if (!$link){
echo('Unable to connect to database');
}
else{
mysql_query("INSERT INTO ban (active, ip, `by`, `date`, reason) VALUES (1,'10.25.47.88', 'AUTOBAN', '12-12-45', 'test')");
}
mysql_close($link);
use mysql error statement in each variable for know which line your mistake occured.
The query probably doesn't display an error because error_reporting is turned of in your php.ini:
try setting error_reporting to E_ALL.
Also the query might not work because you are sending "NULL" as value for banid which is probably a either a primary key or a foreign key / index that doesn't allow a NULL value.
Try this:
INSERT INTO `banlist` (`banid`, `active`, `ip`, `by`, `date`, `reason`) VALUES ('', 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')
As stated, 'by' is reserved keyword, but you can help to MySQL in the parse so it'll know if it's a field name or a command.
EDIT:
I've changed NULL to ''. I'm not sure in this, never tried, but if it's an AI field, maybe you can't use NULL there, just use an empty content as a placeholder for ID field.
Just try this:
INSERT INTO banlist VALUES (NULL, 1, '10.25.47.88', 'AUTOBAN', '12-12-45', 'test')

Beginner PHP: I can't insert data into MYSQL database

I'm learning PHP right now and I'm trying to insert data into a MySQL database called "pumpl2" The table is set up like this.
create table product
( productid int unsigned not null auto_increment primary key,
price int(9) not null,
value int(9) not null,
description text
);
I have a form and want to insert the fields from the form in the database. Here is what the php file looks like.
<?php
// create short variable names
$price = $_POST['price'];
$value = $_POST['value'];
$description = $_POST['description'];
if (!$price || !$value || !$description) {
echo "You have not entered all the required details.<br />"
."Please go back and try again.";
exit;
}
# $db = new mysqli('localhost', 'pumpl', '********', 'pumpl2');
if (mysqli_connect_errno()) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "insert into pumpl2 values
('".$price."', '".$value."', '".$description."')";
$result = $db->query($query);
if ($result) {
echo $db->affected_rows." product inserted into database.";
} else {
echo "An error has occurred. The item was not added.";
}
$db->close();
?>
When I submit the form, I get an error message "An error has occurred. The item was not added."
Does anyone know what the problem is? Thank you!
This should give you more information:
echo "An error has occurred: " . $db->error();
You are trying to insert into the table called pumpl2, but the CREATE TABLE statement created a table called product.
In addition, as ZeissS noted, you have to consider the following:
CREATE TABLE product (
productid int unsigned not null auto_increment primary key,
price int(9) not null,
value int(9) not null,
description text
);
Query OK, 0 rows affected (0.09 sec)
INSERT INTO product VALUES (1, 1, 'test');
ERROR 1136 (21S01): Column count doesn't match value count at row 1
To solve that error, you need to explicitly specify the list of the columns:
INSERT INTO product (price, value, description) VALUES (1, 1, 'test');
Query OK, 1 row affected (0.03 sec)
You only insert three columns but have four defined in your table. Thus you have to name the columns explicitly:
INSERT INTO tableName (ColumnA, ColumnB, ColumnC) VALUES ('A', 'B', 'C')
$query = "insert into pumpl2.product (price, value, description) values('" .
$db->read_escape_string($price) . "', '".
$db->read_escape_string($value) . "', '" .
$db->read_escape_string($description) . "')";
$result = $db->query($query);
And an obligatory XKCD cartoon:
Your query is wrong, you didn't have the columns specified.
Try it with:
"INSERT INTO pumpl2 (price, value, description) VALUES ('".$price."', '".$value."', '".$description."')"
Besides that, do not use the $_POST values to enter them directly into the database. Search for SQL Injection on this one. Use mysql_real_escape_string on the $_POST data first, or even better use prepared statements.
It could be several reasons.
Try
echo "Errormessage: ".$db->error;
to get more details, why the Insert didn't work.
Your table is called products not pumpl2. Furthermore you should do:
insert into product (price, value, description) values ( ...

PHP/MySQL insert row then get 'id'

The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id().
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.
Another way would be to run both queries in one go, and using MySQL's LAST_INSERT_ID() method, where both tables get modified at once (and PHP does not need any ID), like:
mysqli_query($link, "INSERT INTO my_user_table ...;
INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");
Note that Each connection keeps track of ID separately (so, conflicts are prevented already).
The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.
The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().
As to PHP's website, mysql_insert_id is now deprecated and we must use either PDO or MySQLi (See #Luke's answer for MySQLi). To do this with PDO, proceed as following:
$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute([':name' => 'Bob', ':city' => 'Montreal']);
echo $db->lastInsertId();
As #NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php
I just want to add a small detail concerning lastInsertId();
When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.
Consider the following example
$sql = 'INSERT INTO my_table (varNumb,userid) VALUES
(1, :userid),
(2, :userid)';
$sql->addNewNames = $db->prepare($sql);
addNewNames->execute(array(':userid' => $userid));
echo $db->lastInsertId();
What happens here is that I push in my_table two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.
The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the last row, but the id of the first row that was added in the last request.
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row.
Hope this helps.
Try like this you can get the answer:
<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0
I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();
Try this... it worked for me!
$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
$msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Another possible answer will be:
When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.
By this method, you don't have to worry about the id, it'll be made automatically.
For example (taken from w3schools )
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
Hope this will be helpful for someone.
Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

Categories