PHP/SQL Multi INSERT INTO dont work - php

I cant insert 2 tabs at once.
It only insert 1 of them (In this example, it inserts the first one)
function addNewUser($username, $password, $email){
$time = time();
/* If admin sign up, give admin user level */
if(strcasecmp($username, ADMIN_NAME) == 0){
$ulevel = ADMIN_LEVEL;
}else{
$ulevel = USER_LEVEL;
}
$datumregistrationbla = date("d.m.Y");
$q = "INSERT INTO ".TBL_USERS." (username, password, email, userlevel, register_date) VALUES ('$username', '$password', '$email', '$ulevel', '$datumregistrationbla')";
return mysql_query($q, $this->connection);
$q = "INSERT INTO `post` (`post_id`, `from`, `to`, `betreff`, `text`, `datum`, `active`) VALUES ('', 'Fuchsfeuer', '$username', 'Test', 'Test2', '$datumregistrationbla', '0')";
return mysql_query($q, $this->connection);
}

The problem is because you return the first mysql_query and the rest will not be executed.Try removing it like this.
function addNewUser($username, $password, $email){
$time = time();
/* If admin sign up, give admin user level */
if(strcasecmp($username, ADMIN_NAME) == 0){
$ulevel = ADMIN_LEVEL;
}else{
$ulevel = USER_LEVEL;
}
$datumregistrationbla = date("d.m.Y");
$q = "INSERT INTO ".TBL_USERS." (username, password, email, userlevel, register_date) VALUES ('$username', '$password', '$email', '$ulevel', '$datumregistrationbla')";
mysql_query($q, $this->connection);
$q = "INSERT INTO `post` (`post_id`, `from`, `to`, `betreff`, `text`, `datum`, `active`) VALUES ('', 'Fuchsfeuer', '$username', 'Test', 'Test2', '$datumregistrationbla', '0')";
mysql_query($q, $this->connection);
}
Please forget using mysql_* because it is deprecated and in php 7 it was already removed.
Try to use mysqli or pdo

Related

How last_id works?

The customer sql is inserted the others are not. Help. Thanksss
I have sql for customer_tbl, transaction_tbl, and order_tbl.
customer_no, transaction_no and orderlist_no are A_I.
This is my code so far.
$x=0;
while ($x!=5) {
$product_sku[$x] = $_POST['productsku[$x]'];
$quantity[$x] = $_POST['productqty[$x]'];
$x=$x+1;
}
$sqlc = "INSERT INTO customer_tbl(customer_name, fb_url, mobile_no, email_address, address) VALUE ('$customer_name', '$fb_url', '$mobile_no', '$email', '$address');";
mysqli_query($conn, $sqlc);
$last_id = mysqli_insert_id($conn);
$sqlt = "INSERT INTO transaction_tbl(customer_no, transaction_type, status, transaction_date, deadlinepay_date, payment_mode, delivery_option) VALUE ('$lastid', 'OL-', '1', CURRENT_TIMESTAMP(), '$deadlinepay_date', '$payment_mode', '$shipping_option');";
mysqli_query($conn, $sqlt);
$last_id = mysqli_insert_id($conn);
$x=0;
while ($x!=5) {
if (!empty($product_sku[$x])) {
$sqlo = "INSERT INTO order_tbl(transaction_no, product_sku, quantity) VALUES ('$last_id', '$product_sku', '$quantity');";
mysqli_query($conn, $sqlio);
}
$x=$x+1;
}
In your code, you have $last_id = mysqli_insert_id($conn); but in your query, you have ...VALUE ('$lastid'....
So change $lastid to $last_id or the other way around.
You should keep naming your variables consistent to avoid confusion in the future.

unable to perform query using mysqli_query

$name = mysqli_real_escape_string($connection, $_POST["name"]);
$surname = mysqli_real_escape_string($connection, $_POST["surname"]);
$username = mysqli_real_escape_string($connection, $_POST["username"]);
$email = mysqli_real_escape_string($connection, $_POST["email"]);
$pw1 = mysqli_real_escape_string($connection, $_POST["pw1"]);
$query = "INSERT INTO 'users' ('id','name', 'surname', 'username', 'email', 'password') VALUES (NULL,'$name', '$surname', '$username', '$email', '$pw1')";
$result = mysqli_query($connection, $query);
if(!$result){
echo ("fail");
}
I test if the query has worked using if(!$result){ echo ("fail");} and it echoes fail every time and no data is inserted into the database every time! I have checked the syntax and i believe it is correct... could this be because of the database "collation"?
You should not use the single quote at the table or field name. You have to use a Backtick (like ``) which is located in under Esc key or left side of 1 Key or upper side of Tab key. It should looks like:
$query = "INSERT INTO `users` (`id`, `name`, `surname`, `username`, `email`,
`password`) VALUES ('null', '$name', '$surname', '$username', '$email', '$pw1')";
or
$query = "INSERT INTO users (id, name, surname, username, email,
password) VALUES ('null', '$name', '$surname', '$username', '$email', '$pw1')";
Note: If your id field is already set auto increment then you can remove id and value null. Because id value will automatically increment.
Hope it will helpful.

Multiple queries & LastInsertId

How wrong is that query? Can I insert multiple queries like that?
Can I use lastInsertId like that?
$pdo = Database::connect();
$dflt = 'DEFAULT';
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', :nome, :dt_registo, :tipo, :activo)";
$stmt = $pdo->prepare($query1);
$stmt->execute();
$insertedid = $pdo->lastInsertId("utilizador");
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade,'$insertedid')";
$stmt2 = $pdo->prepare($query2);
$stmt2->execute();
$hashed_password = hash( 'sha512', $_POST['password']);
$stmt->bindParam(':email',$_POST['email']);
$stmt->bindParam(':nome',$_POST['nome']);
$stmt->bindParam(':dt_registo',$dflt);
$stmt->bindParam(':tipo',$dflt);
$stmt->bindParam(':activo',$dflt);
$stmt->bindParam(':morada',$_POST['morada']);
$stmt->bindParam(':cpostal',$_POST['cpostal']);
$stmt->bindParam(':cidade',$_POST['cidade']);
if($stmt->execute()){
echo "Product was created.";
}else{
echo "Unable to create product.";
}
Database::disconnect();
}
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
I've already been searching but couldn't find how to use both in a query and I already expired all the solutions, not sure which is wrong.
EDIT:
I'm starting to think its more than the query, if someone notice something..
JAVASCRIPT
$(document).on('submit', '#create-aluno-form', function() {
// show a loader img
$('#loader-image').show();
// post the data from the form
$.post("registar.php", $(this).serialize())
.done(function(data) {
// show create product button
$('#create-aluno').show();
showProducts();
});
return false;
});
Most likely your statement fails to insert, Your code is full of problems:
You used prepare statement but yet you put values in the query string
hashed_password is undefined in the first query
You try to bind multiple queries at once
wrong order prepare the first query, execute , then bind the parameters
-$pdo->lastInsertId(); is enough not sure why you pass "utilizador"
Try this approach:
try{
$pdo = Database::connect();
$dflt = 'DEFAULT';
$hashed_password = hash( 'sha512', $_POST['password']);
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, :pass, :nome, :dt_registo, :tipo, :activo)";
$stmt = $pdo->prepare($query1);
$stmt->bindParam(':email',$_POST['email']);
$stmt->bindParam(':pass',$hashed_password);
$stmt->bindParam(':nome',$_POST['nome']);
$stmt->bindParam(':dt_registo',$dflt);
$stmt->bindParam(':tipo',$dflt);
$stmt->bindParam(':activo',$dflt);
if($stmt->execute()){
//query1 success
$insertedid = $pdo->lastInsertId();
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade, :utilizador_id)";
$stmt2 = $pdo->prepare($query2);
$stmt2->bindParam(':morada',$_POST['morada']);
$stmt2->bindParam(':cpostal',$_POST['cpostal']);
$stmt2->bindParam(':cidade',$_POST['cidade']);
$stmt2->bindParam(':utilizador_id',$insertedid);
if($stmt2->execute()){
//query2 success
}else{
//query2 failed
}
}else{
//query1 failed
}
Database::disconnect();
}
catch(PDOException $exception){
echo "Error: " . $exception->getMessage();
}
Try this....
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', nome, :dt_registo, :tipo, :activo);";
$stmt = $pdo->prepare($query1);
$stmt->execute();
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade, LAST_INSERT_ID());";
$stmt2 = $pdo->prepare($query2);
$stmt2->execute();
Because insert the query not get last insert id. so separate those queries
You have to use the
mysql_insert_id()
to get the last inserted record's id
I think these will useful to you.
$query = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', nome, :dt_registo, :tipo, :activo)";
$query_1 = " INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
VALUES (:morada, :cpostal, :cidade, mysql_insert_id())";
$stmt = $pdo->prepare($query);
$stmt_1 = $pdo->prepare($query_1);
these will useful to you.
mysql_select_db('test');
mysql_query("INSERT INTO mytable (name) values ('venkatesh')");
printf("Last inserted record has id %d\n", mysql_insert_id());
Thank you.
see here
INSERT INTO questions VALUES(NULL, 'My question');
INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 1');
INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 2');
INSERT INTO answers VALUES(NULL, LAST_INSERT_ID(), 'Answer 3');
Now I Have using LAST_INSERT_ID();
INSERT INTO answers VALUES
(NULL, LAST_INSERT_ID(), 'Answer 1') ,
(NULL, LAST_INSERT_ID(), 'Answer 2') ,
(NULL, LAST_INSERT_ID(), 'Answer 3');
OR
also we can try this way
INSERT INTO questions VALUES(NULL, 'My question');
SET #id = (SELECT LAST_INSERT_ID());
INSERT INTO answers VALUES(NULL, #id, 'Answer 1');
INSERT INTO answers VALUES(NULL, #id, 'Answer 2');
INSERT INTO answers VALUES(NULL, #id, 'Answer 3');
It was just an example for you
$query1 = "INSERT INTO utilizador(email, pass, nome, dt_registo, tipo, activo)
VALUES (:email, '$hashed_password', nome, :dt_registo, :tipo, :activo);";
$stmt = $pdo->prepare($query1);
$stmt->execute();
$insertedid = $pdo->lastInsertId("utilizador");
$query2 ="INSERT INTO aluno(morada, cd_postal, cidade, utilizador_id)
Ref link:-http://www.dreamincode.net/forums/topic/169597-pdolastinsertid/
VALUES (:morada, :cpostal, :cidade,'$insertedid'
);";
$stmt2 = $pdo->prepare($query2);
$stmt2->execute();

INSERT query of xampp MySQL doesn't work

This php insert query is not working in MYSQL xampp. I couldn't find any error
QUERY:
$query = "INSERT INTO member (id, username,fname,lname,email, password, salt )
VALUES ( '$username', '$password', '$email', '$salt' )";
you are missing $fname, $lname in query also use NULL for id if auto incremented
$query = "INSERT INTO member (id, username,fname,lname,email, password, salt )
VALUES (NULL, '$username', '$fname', '$lname', '$password', '$email', '$salt' )";
you are passing wrong number of column names.your correct query should look like this:
$query = "INSERT INTO member (username,password,email,salt )
VALUES ( '$username', '$password', '$email', '$salt' )";
You are not inserting values to all the columns specified in the query.
In your query
$query = "INSERT INTO member (id, username,fname,lname,email, password, salt )
VALUES ( '$username', '$password', '$email', '$salt' )";
You are specifying 7 columns and only 4 values .So either add more values or remove unnecessary columns specified in the query like
$query = "INSERT INTO member (username, password,email, salt )
VALUES ( '$username', '$password', '$email', '$salt' )";
OR
$query = "INSERT INTO member (id, username,fname,lname,email, password, salt )
VALUES ('$id', '$username','$fname','$lname','$email', '$password', '$salt' )";

PHP Mysql Query (INSERT) Issue

I am having an issue with a MySQL query as follows:
My script generates this as an example query:
INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('Test2', '123-456-7890', 'test#test.com', 'mesa', 'az', '04-14-2013')
Which if I drop directly into PHPMyA, works fine. However, the PHP script I am trying to use to send the query from my website is not working and I can't get it figured out. Here it is:
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
mysql_query($sql);
$result = mysql_query($sql);
if($result)
{
echo("<br>Data Input OK");
}
else
{
echo("<br>Data Input Failed");
}
Nothing makes it to the MySQL DB and no PHP errors are displayed, however, if I echo $sql I get the exact query I posted previously.
Just remove the single line mysql_query($sql); on your code and you will be fine.. But you should better start practicing PHP MySQLi which stands for PHP MySQL Improved, such:
$con = mysqli_connect($host, $user, $password, $password);
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
$result = mysqli_query($con, $sql);
if($result) {
echo("<br>Data Input OK");
} else {
echo("<br>Data Input Failed");
}
$sql = 'INSERT INTO Table_name (`id`, `name`) VALUES ("1", "php");
You are executing $sql twice in your script wich is causing the error, please remove
mysql_query($sql);
And it will be ready to go
I would also suggest to stop using mysql_query please switch to mysqli or PDO
Are you sure there is a valid connection (..mysql_connect())? Try using the full syntax like so..
$conn = mysql_connect(...);
$result = mysql_query($query, $conn);
Also try forcing a commit after you execute the statement -
$mysql_query("COMMIT", $conn);
You are running mysql_query twice. Reason of the error. Try running the following code.
$sql = "INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$name', '$phone', '$email', '$city', '$state', '$date')";
$result = mysql_query($sql) or die(mysql_error());
if($result){
echo("<br>Data Input OK");
} else{
echo("<br>Data Input Failed");
}
use this
"INSERT INTO `contacts`(`name`, `phone`, `email`, `city`, `state`, `date`) VALUES ('$_POST[name]', '$_POST[phone]', '$_POST[email]', '$_POST[city]', '$_POST[state]', '$_POST[date]')";
Try to use mysql_query($sql,$con); instead of mysql_query($sql);.
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$age=$_POST['age'];
$address=$_POST['address'];
$ins="insert into table_name(`name`,`age`,`address`)values('".$name."','".$age."','".$address."')";
mysql_query($ins);
echo 'data inserted successfully';
}

Categories