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

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 ( ...

Related

Listing username with bid items - PHP

I'm fairly new to PHP and I'm trying to make a simple auction website. I think I've run into my first problem.
What I'm trying to do is let a registered user add an item to the auction. I can do this just fine. However, I also need to keep track of the user that put the item up for bidding. I thought I could get the accountid by inserting the accountid from the current session into my table, but I keep getting an error saying accountid is an unknown column in my field list.
Here is the code where I create the table.
$sql = "CREATE TABLE biditems (
itemid INT(100) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
accountid INT(100),
biditem VARCHAR(30) NOT NULL,
biddesc tinytext
)";
And to add the items.
$accountid=$_SESSION['accountid'];
$item=$_POST['item'];
$description=$_POST['description'];
$sql= "INSERT INTO biditems (accountid, biditem, biddesc) VALUES
('$accountid', '$item', '$description')";
Your query looks fine. I have also tested it.
Did you double check that the structure of your table is correct?
If you can insert a row via phpMyAdmin or the MySQL Workbench try this and afterwards run a select query like
$rows = "SELECT * FROM biditems";
while ($row = mysql_fetch_array($rows)) {
var_dump($row);
}
Something like this just to make sure.
You should make some sql injection escape first. And if you did it - you should add the variables properly. I did not wrote you some injection escape. You can see sprintf instructions for example.
<?php
$accountid=$_SESSION['accountid'];
$item=$_POST['item'];
$description=$_POST['description'];
$sql= "INSERT INTO biditems (accountid, biditem, biddesc) VALUES
('" . $accountid . "', '" . $item . "', '" . $description . "')";

Why wont this MySQL Query save

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

insert an array into table using for loop

I am trying to insert rows of data in an array into a table in mysql database. I am a beginner in php, mysql and have very little knowledge about it. I just want to learn more. If you can give this a try It would be great.
The code which i want to insert is below:
for($x=0; $x<2; $x++)
{
$data[$x]['title'] = $titleQuery->item($x)->nodeValue;
$data[$x]['titleHrefQuery'] = $titleHrefQuery->item($x)->nodeValue;
$data[$x]['food'] = $foodQuery->item($x)->nodeValue;
$data[$x]['locality'] = $localityQuery->item($x)->nodeValue;
$data[$x]['rating'] = $ratingQuery->item($x)->nodeValue;
$data[$x]['cost'] = $costQuery->item($x)->nodeValue;
}
I am tring to insert using the code given below:
$query = "INSERT INTO table (`title`, `link`, `food`, `locality`, `rating`, `cost`) VALUES
('" . $titleQuery->item($x)->nodeValue . "',
'".$titleHrefQuery->item($x)->nodeValue."',
'".$foodQuery->item($x)->nodeValue."',
'".$localityQuery->item($x)->nodeValue."',
'".$ratingQuery->item($x)->nodeValue."',
'".$costQuery->item($x)->nodeValue."')";
$result = mysql_query($query);
if($result)
{
echo ("Success");
}
else
{
echo ("Not added");
}
But every time it shows not added. please help!!
Change
INSERT INTO table
to
INSERT INTO `table`
Because table is a reserved keyword.And if you are using reserved keywords as table name or column name then you must enclose them in back-ticks (`).And its better not to use any reserve keyword.So if you can change the name then it will be the best choice.You can check for more in these questions
How do I escape reserved words used as column names? MySQL/Create Table
Can we have the table name as "option" in MySQL?
H2 database column name "GROUP" is a reserved word
"INSERT INTO table...." should be "INSERT INTO `table`..."
Try to avoid mysql key names as table name or field name it would help you in writing better sql queries.
Use following line to see mysql error so can you easily track the reason why you are getting error -
if($result)
{
echo ("Success");
}
else
{
echo ("Not added");
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
}

Update statement not updating table but inserting new entry into table instead

For the life of me I cannot figure out why my update statement will not update the table row but instead it creates a new row. I have an ID column that is the unique identifier and is auto_increment, I am just not sure if you can update an auto_incremented data set the way i am trying to.
I have a form that is echo'ing data from the database into the fields and then am using it to edit the fields and update them.
The code:
<?php
$EntryID = $_GET['Eid'];
$IDlist = mysql_query("SELECT * FROM BD WHERE Id='$EntryID'");
$IDresults = mysql_fetch_array($IDlist);
$update_query = "UPDATE `BD` SET `Id` ='$IDresults['Id']',`EntryTitle` = '$MyTitle',`EntryDescription` = '$MyDescription',`Category` = '$MyCategory' WHERE `Id` ='$EntryID'";
mysql_query($update_query);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else{
header('location: /admin/bd-edit-entry.php?sub=1');
exit();
}
mysql_close($con);
?>
Any help or advice would be a great.
SET `Id` ='$IDresults['Id']'
should be either:
SET `Id` ='$IDresults[Id]'
or
SET `Id` ='{$IDresults['Id']}'
If you turn on error reporting, you should get errors about a bad index.
Or you can leave this column out of the update entirely, since this column isn't changing.

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