Insert in MySQL Not Working - php

I am trying to put data in MySQL with PHP but is not showing any error but values are not entered in database too.
$query = "INSERT INTO orders (username, servicename, link, quantity, cost, date)
VALUES('$username', '$service_name', '$link', '$quanitiy', '$cost', '$date')";
$insert=mysqli_query($db, $query);

I think your query should look something like that:
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// create the query
$query = "INSERT INTO orders (username, servicename, link, quantity, cost, date)
VALUES('$username', '$service_name', '$link', '$quanitiy','$cost', '$date')";
// preform the query
$insert=mysqli_query($conn, $query);
// you need to check if the insert succeeded before closing the connection
// close connection to DB
mysqli_close($conn);

Related

Get ID from last insert into table

Im inserting into multiple tables , and need to get the ID from the last insert into table1 and use that as a variable in the insert for table 2.
The IDs is auto incremented.
The query's will be run once a submit button has been clicked in a form.
Query's:
$sql = "INSERT INTO table1 (Text) VALUES ($T1text);";
$sql = "INSERT INTO table2 (table1ID,Text) VALUES ($table1id, $T2text);";
table1 {id,Text}
table2 {id,table1.id,Text}
There is a PHP function for that (Decprecated, Removed in 7.0 !)
Or the according mysql/mysqli/pdo functions.
Solutions
PHP (Deprecated)
Example
$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());
Source: http://php.net/manual/en/function.mysql-insert-id.php
Mysql/Mysqli/PDO
Mysqli
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
PDO
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
Source: http://www.w3schools.com/php/php_mysql_insert_lastid.asp

SQL error inserting into table

I keep getting this error in my php. It worked fine when I hard set the values but doesn't seem to work with variables.
Error: INSERT INTO ContactUS (name, email, subscribed) VALUES (TEST, my#email.com, 1)
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 'Anis, my#email.com, 1)' at line 1
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ($name, $email, $subscribed)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Values should be quoted:
$sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ('$name', '$email', '$subscribed')";
Perhaps it's better to use prepared statements as this is done automatically for you and you won't be vulnerable to SQL injections.
Use quotes around variables, as PHP will replace its value, leaving an invalid query:
$sql = "INSERT INTO ContactUS (name, email, subscribed) VALUES ('$name', '$email', '$subscribed')";
but please use prepared statements, otherwise you'll be victim of SQL injection

How to insert data into MySQL using MySQLi?

I am new to using MySQLi. I try to use MySQLi in order to insert data in my database. But does not work. Where may be the error?
echo 'connected';
$con = mysqli_connect("localhost",$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// mysqli_select_db($con,"kraus");
$firstname = $_POST['uname'];
$lastname = $_POST['address'];
$age = $_POST['pass'];
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
mysqli_query($con,$sql);
echo "1 record added";
mysqli_close($con);
Why is line this commented out? You are selecting the database in mysqli_connect("localhost","root","root","kraus") but it makes no sense why that is there:
// mysqli_select_db($con,"kraus");
Should you not have that commented like this?
mysqli_select_db($con,"kraus");
Also there is no space here between registration and the fields in (…) as well as the quotes around your fields:
$sql = "INSERT INTO registration('uname', 'address', 'password') VALUES ('$firstname', '$lastname', '$age')";
That should be like the following with a space added between the table name & the fields. And since there should just be no quotes around your field names so the final query should be this:
$sql = "INSERT INTO registration (uname, address, password) VALUES ('$firstname', '$lastname', '$age')";
Or perhaps have back ticks like this:
$sql = "INSERT INTO registration (`uname`, `address`, `password`) VALUES ('$firstname', '$lastname', '$age')";
Also, you should really refactor & cleanup your whole codebase like this:
// Set the connection or die returning an error.
$con = mysqli_connect("localhost","root","root","kraus") or die(mysqli_connect_errno());
echo 'connected';
// Select the database.
// mysqli_select_db($con, "kraus");
$post_array = array('uname','address','pass');
foreach ($post_array as $post_key => $post_value) {
$$post_key = isset($_POST[$post_value]) && !empty($_POST[$post_value]) ? $_POST[$post_value] : null;
}
// Set the query.
$sql = "INSERT INTO registration (uname, address, password) VALUES (?, ?, ?)";
// Bind the params.
mysqli_stmt_bind_param($sql, 'sss', $uname, $address, $pass);
// Run the query.
$result = mysqli_query($con, $sql) or die(mysqli_connect_errno());
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
echo "1 record added";
Note how I am using mysqli_stmt_bind_param and also setting an array of $_POST values & rolling throughout them. Doing those two basic things at least enforce some basic validation on your input data before it gets to the database.
You have quotes around the column names in your query. Maybe you meant to use backticks instead:
(`uname1`, `address`,...)
You are also vulnerable to sql injection. Look into mysqli prepared statements.

Can't insert data to MySQL using PHP

I have been trying to get my form data to database through PHP code but it is not working and I have looked at the code a thousandth times for a possible error but couldn't find one as a beginner. The form will actually submit but nothing gets to the database.
Any fast help would be deeply appreciated. Here is the code:
$conn = #mysqli_connect('localhost', 'root', 'aboki');
if (mysqli_connect_error()) {
die('Connect Error: ' . mysqli_connect_error());
}
$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday) values ($email, $firstName, $surname, $userName, $password, $userDOB)";
$result = mysqli_query($conn, $qry);
try this
$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday)
values ('$email', '$firstName', '$surname', '$userName', '$password', '$userDOB')";
Firstly, you are not quoting the values which is why it is not inserting...
This will fix it (But I strongly recommend you do not use this method!):
$qry = "INSERT INTO users (email, firstName, surname, userName, password, birthday) values ('$email', '$firstName', '$surname', '$userName', '$password', '$userDOB')";
The Correct Method
You would be better off making the most of the predefined functions that mysqli offers and binding these parameters in a prepared statement like so:
mysqli_prepare($conn,"INSERT INTO users (email, firstName, surname, userName, password, birthday) values (?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($conn, 'TYPES_HERE',$email, $firstName, $surname, $userName, $password, $birthday)
I have solution for data Insert , You can try it out.
$conn= mysqli_connect("localhost", "root", "my_password", "world");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "INSERT INTO users
(email, firstName, surname, userName, password, birthday) VALUES
($email, $firstName, $surname, $userName, $password, $userDOB)";
mysqli_query($conn, $query);
printf ("New Record has id %d.\n", mysqli_insert_id($link));
mysqli_close($link);
As you having mysqli in Query the syntax quite different,
Feel free to ask further Question.
Thanks
example:
$stmt = mysqli_prepare($conn, "SELECT District FROM City WHERE Name=?")) {
$stmt->bind_param("s", $city);
$stmt->execute();

Php Post to two tables in Mysql

I'm trying to POST to two tables at the same time. I'm trying to get the DonorID to display in to another table under $description. I'm able to just write any text in the $description, but I need it to be dynamic not static, which is what the text is. I have two tables; the first is accounting and the second is donations. I'm trying to alter the $description='Donation from Donor'; and have the donor that made the transaction be listed where the Donor is. Any suggestions would be greatly appreciated.
Here is my code:
<?php
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
$con = mysql_connect("$dbserver","$dblogin","$dbpassword");
if (!$con)
{
die('Could not connect to the mySQL server please contact technical support
with the following information: ' . mysql_error());
}
mysql_select_db("$dbname", $con);
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO accounting (date, transactiontype, account,
description, Income, Expense)
VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
mysql_query($sql2);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
header( 'Location: http://localhost/donations.php' ) ;
?>
As i said i would personaly use mysqli for new project, here a sample of you code with mysqli:
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
//opening connection
$mysqli = new mysqli($dbserver, $dblogin, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO `donations` (`date`, `firstname`, `middleinitial`, `lastname`, `organization`, `donorid`, `paymenttype`, `nonmon`, `Income`, `event`) Values ('$date','$firstname','$middleinitial','$lastname','$organization', '$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
$query1 = $mysqli->query($sql) or die($mysqli->error.__LINE__);
$query2 = $mysqli->query($sql2) or die($mysqli->error.__LINE__);
//closing connection
mysqli_close($mysqli);
header( 'Location: http://localhost/donations.php' ) ;
UPDATE
you can add donorid simply placing both vars in the query like:
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('".$date."','".$transactiontype."','".$account."','".$donorid . " " . $description."','".$Income."','".$Expense."')";
this way i just separate donorid and description with a space but you can add anything you want to in plain text:
'".$donorid . " - " . $description."'
After this
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
put
mysql_query($sql);
Please execute the query.
Things I see is ..
First your just executing your $sql2 but not the other $sql statement
Another is while inserting you declared some columns name that is a mysql reserved word (date column)
you should have `` backticks for them..
Refer to this link MYSQL RESEERVED WORDS
additional note: Your query is also vulnerable to sql injection
SQL INJECTION
How to prevent SQL injection in PHP?
Just write after insert on trigger on first table to insert data into another table.
You will have to split $sql2 to 2
1st :-
$sql2 = "INSERT INTO accounting (description) SELECT * FROM donations WHERE donorid='$donorid'"
then another one
"UPDATE accounting SET date='', transactiontype='', account ='', Income='', Expense ='' WHERE description=(SELECT * FROM donations WHERE donorid='$donorid')"
that will take all the information from donoation for the given donorid and list it under description in accounting

Categories