Related
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.
In my Joomla 2.5.14 I'm trying to insert the current page_id, user_id and date into a mySQL table (called xmb9d_hist).
This is the code I'm using:
<?php
/* Define $jinput */
$jinput = JFactory::getApplication()->input;
/* Get the current page id */
$page= $jinput->get('id');
/* Get the current user id */
$user =JFactory::getUser();
$usr_id = $user->get('id');
/* Get the current date */
$date =JFactory::getDate();
/* Open a connection */
$link=mysqli_connect('localhost','peter','abc123');
if(!$link){
echo "Não há ligação!";
exit();
};
/* Insert current user id, page id and date in to table xmb9d_hist */
mysqli_query($link, "INSERT INTO `portalge_formacao`.`xmb9d_hist` (`user_id`, `page_id`, `date`) VALUES ($usr_id, $page, $date)");
/* Close connection */
mysqli_close($link);
?>
The first part of the code is working ok (retrieving the values for the 3 variables. However, the data isn't being inserted in the database and no error is produced.
In MySQL table, user_id and page_id are defined as INT(11) and date as date.
Thanks in advance for your help.
You need to stick to Joomla coding standards when using Joomla unless they have not provided a class for whatever you need. Have a read of the documentation before trying something just incase there is information about it.
Try using the following:
<?php
$db = JFactory::getDbo();
$date = JFactory::getDate();
$user = JFactory::getUser();
$jinput = JFactory::getApplication()->input;
$page= $jinput->get('id');
$usr_id = $user->get('id');
$query = $db->getQuery(true);
$columns = array('user_id', 'page_id', 'date');
$values = array($usr_id, $page, $date);
$query
->insert($db->quoteName('#__hist'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
$db->setQuery($query);
?>
Hope this helps
I see a few issues with your insert query. First off, I believe that JFactory::getDate() returns an object, so to get something you can insert into the database you want to do a toFormat() on it. Try changing your line from:
$date =JFactory::getDate();
to this:
$date =JFactory::getDate()->toFormat();
And since the date isn't an integer, you need to escape the string in your insert, so update that line to this:
mysqli_query($link, "INSERT INTO `portalge_formacao`.`xmb9d_hist` (`user_id`, `page_id`, `date`) VALUES ($usr_id, $page, '$date')");
You should use the method toSql() , it's for SQL e.g.
$date = JFactory::getDate()->toSql();
hope this helps
I inserted data through the phpmyadmin into my table. It shows me the query it uses so I copied and pasted it into my php code.
My Php code is suppose to be submitting a form and I am trying to get $_POST('name') into the query.When I run the code it fills everything out but the version_name field where name goes.
Funny thing is im using the same MYSQL query that inserts it correctly on the phpmyadmin.
I have moved on to trying a random name not the POST to see if it submits but i keep getting a blank... any suggestions?
$sql = "INSERT INTO `Prototype`.`Version` ('version_id', `version_name`, `version_status`, `created_date`, `created_by`) VALUES ('','A', 'A', CURRENT_TIMESTAMP, NULL);";
this is the Insert part, and I have also tried removing the version_id since it is autoincramented but no help.
the first row is what the result looks like when submitted from my php. the second row is when I insert it right from phpmyadmin.
Any help getting version_name to be submitted from my php would be wonderful!
edit----
Heres my php code
<?php
// Retrieve form data
$name = $_POST['name'];
if (!$name) {
echo "save_failed";
return;
}
$db = array(
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'Prototype',
);
$link = #mysql_connect($db['host'], $db['login'], $db['password']);
if (!$link) {
echo "save_failed";
return;
}
mysql_select_db($db['database']);
// Clean variables before performing insert
$clean_name = mysql_real_escape_string($name);
// Perform insert
$sql = "INSERT INTO `Prototype`.`Version` (`version_name`, `version_status`, `created_date`, `created_by`) VALUES ( 'A', 'A', CURRENT_TIMESTAMP, NULL);";
if (#mysql_query($sql, $link)) {
echo "success";
#mysql_close($link);
return;
} else {
echo "save_failed";
#mysql_close($link);
return;
}
?>
firs thing first $_POST('name'); is nothing $_POST['name']; is right. Now answer to your question use following query.
$sql = "INSERT INTO `Prototype`.`Version` (`version_name`, `version_status`, `created_date`, `created_by`) VALUES ('A', 'A', CURRENT_TIMESTAMP, NULL)";
I have also checked it on my own table made from structure provided by you.
it's query is given below.
CREATE TABLE `proto` ( `version_id` int(3) NOT NULL AUTO_INCREMENT, `version_name` varchar(45) NOT NULL, `version_status` varchar(45) NOT NULL, `created_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `created_by` varchar(45) DEFAULT NULL, PRIMARY KEY (`version_id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
Below code is for you to submit it via php.
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO("mysql:host=".HOST.";dbname=".DBNAME.";charset=utf8", USERNAME, PASSWORD, $options);
$query = $db->prepare("INSERT INTO `Prototype`.`Version`
(`version_name`,
`version_status`,
`created_date`,
`created_by`)
VALUES
('A',
'A',
CURRENT_TIMESTAMP,
NULL)");
$result = $query->execute();
return $result ? true : false;
This many be by the by, and not an answer to your question but in Mysql 4 this would work:
An auto increment value can be
left out completely, if you state named fields
NULL
0
'' (empty string)
From Mysql 5 the last one will not work.
It was an undocumented feature of Mysql 4 which was removed for Mysql 5.
It was an error with the server. I deleted the database and started from scratch and it solved the issue. Almost went as far as uninstalling and reinstalling xampp.
So i have so code that takes a message/post users insert and its meant to post it to a database and this then displays and a seperate page. Ive got the displaying park working fine its just trying to insert to database which is the problem
This code...
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$time = time();
mysql_query "INSERT INTO threads (title, message, author, dated);"
VALUES (NULL,'$_POST[title]','$_POST[message]','$_POST[author]','0','$time');
echo "Thread Posted.<br><a href='Untitled9.php'>Return</a>";
?>
wont post the infomation into the database!
Why is this and how can it be resolved?
id int(11) No None AUTO_INCREMENT
title varchar(255) latin1_swedish_ci No None
message text latin1_swedish_ci No None
author varchar(255) latin1_swedish_ci No None
replies int(11) No None
posted varchar(255) latin1_swedish_ci No None
votes_up int(11) No 0
votes_down int(11) No 0
Update:
Should be posted not dated.
Heres your problem:
mysql_query "INSERT INTO threads (title, message, author, posted);"
VALUES (NULL,'$_POST[title]','$_POST[message]','$_POST[author]','0','$time');
Change it to:
mysql_query("INSERT INTO threads (title, message, author, posted) VALUES ('$_POST[title]','$_POST[message]','$_POST[author]','$time');");
I see you have null values also, this makes me believe your using an ID with an auto increment, if this is the case, you need to supply this also. Example:
Edit: Here
mysql_query("INSERT INTO threads (id,title, message, author, posted) VALUES (NULL,'$_POST[title]','$_POST[message]','$_POST[author]','$time');");
Note inserting values straight from post data is unsafe and leaves you open to various attacks.
The values you are trying to add to the new row are more that the assigned values .
mysql_query "INSERT INTO threads (title, message, author, dated);"
that are 4 values you want to set
VALUES (NULL,'$_POST[title]','$_POST[message]','$_POST[author]','0','$time');
and you are assigning 6 values.
which is not possible
Also validate $_POST data = read this Never trust user input.
And read the manual PHP & MYSQL
The semicolon was ending your sql statment. Your query wasn't finished. You still needed to specify the values you wanted to insert.
mysql_query "INSERT INTO threads (title, message, author, dated);"
VALUES ('$_POST[title]','$_POST[message]','$_POST[author]','$time');
You ended the String to early. Should be:
mysql_query("INSERT INTO threads (title, message, author, dated)
VALUES ('$_POST[title]','$_POST[message]','$_POST[author]','$time')");
Also, your code is very likely to become a target of SQL-Injections. You should use the MySQLi-class and a PreparedStatement to insert your posts.
Number of issues :
if you put $_POST[] inside a string you need to put it in braces {$_POST[]} or PHP will not decipher the variable
next the names of the variables in the $_POST[] need to be quoted so that PHP does not think they are CONSTANTS, so they need to be like $_POST['title'] or $_POST["title"]
As others have said you need to protect against SQL injection by filtering the posted vars. Safest way to do this is to use PDO and I have included an example below. You can improve on this.
turn on error reporting so you can see errors while debugging
Here's tested code:
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 'On');
$user='root';
$pass='';
$dsn = 'mysql:dbname=test;host=localhost'; //for PDO later
mysql_connect("localhost",$user , $pass);
mysql_select_db("test");
$time = time();
if (isset($_POST) && !empty($_POST))
{
// using braces {}
$sql=<<<SQL
INSERT INTO threads (title, message, author, posted)
VALUES ('{$_POST['title']}','{$_POST['message']}','{$_POST['author']}','$time')
SQL;
echo "$_POST[title]"."Thread Posted.<br><a href='Untitled9.php'>Return</a>";
// now a PDO version of the same
try {
$pdo = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();die;
}
$sth = $pdo->prepare("INSERT ino threads (title, message, author, posted)
VALUES (:title,:message,:author,:posted)");
$sth->execute(array(':title' => $_POST['title'],':message' => $_POST['message'], ':author' => $_POST['author'] ,':posted' => $time));
echo "Affected rows=".$sth->rowCount().",we are on line=".__LINE__."<br />";
echo $_POST['title']." Thread Posted.<br><a href='Untitled9.php'>Return</a>";
} // close if $_POST
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.