If statement on PHP (inserting data) - php

I have to register a costumer and/or a manager into the database. I just have one form for the information, the only difference is the ID number (valid for managers). The costumers should leave this form blank. I was trying to save the data just using an if statement (If it is blank, save the information in costumer table. If it is not, save in manager). I have not seen this on my classes so I am not sure if it is possible.
Is it possible to use an if statement to insert data? What I mean is, I have two different tables but just one form (one of the forms will make the difference for which table the data will be saved.
The data in the manager table is ok, but when I try to insert data into costumer it is not working. I am not sure that I can use this.
if($_SESSION['id'] != null){
$sql = "INSERT INTO manager (id,magname,maglname,maguser,magpass) VALUES (?, ?, ?, ?, ?);";
$sth = $DBH->prepare($sql);
$sth->bindParam(1, $_SESSION['id'], PDO::PARAM_INT);
$sth->bindParam(2, $_SESSION['firstname'], PDO::PARAM_INT);
$sth->bindParam(3, $_SESSION['secondname'], PDO::PARAM_INT);
$sth->bindParam(4, $_SESSION['username'], PDO::PARAM_INT);
$sth->bindParam(5, $_SESSION['password'], PDO::PARAM_INT);
$sth->execute();
}
if(empty($_SESSION['id']){
$sql = "INSERT INTO costumer (fisrtname,lastname,username,password) VALUES (?, ?, ?, ?);";
$sth = $DBH->prepare($sql);
$sth->bindParam(1, $_SESSION['firstname'], PDO::PARAM_INT);
$sth->bindParam(2, $_SESSION['lastname'], PDO::PARAM_INT);
$sth->bindParam(3, $_SESSION['username'], PDO::PARAM_INT);
$sth->bindParam(4, $_SESSION['password'], PDO::PARAM_INT);
$sth->execute();
}

you can do it directly through following code
if(isset($_SESSION['id']))
$sql = "INSERT INTO `manager`..."
else
$sql = "INSERT INTO `customer`..."

or something like this
if(!empty($_SESSION['id']))
{ $sql = "INSERT INTO `manager`..."}
else
{ $sql = "INSERT INTO `customer`..."}

Related

How to perform the following insert, mysql

I have two tables, reports and events, each table has a unique identifier called id with Auto increment, the problem is that the id in each table is not the same because a report can have events but maybe not. I would like to make a double insert but one column in each table must have an unique key. I do this with the following function:
function addactioneventuser(){
try {
$this->conn->beginTransaction();
$query = "INSERT INTO
" . $this->table_name . "
SET
case_id = ?,
from_to = 0,
action_id = ?,
accepted = 0,
message = ?";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind values
$stmt->bindParam(1, $this->case_id);
$stmt->bindParam(2, $this->action_id);
$stmt->bindParam(3, $this->message);
// execute the query
$stmt->execute();
// insert event query
$query2 = "INSERT INTO event_case
SET
title = ?, body = ?, class = ?, start = ?, end = ?, case_id= ?, worker_id = ?";
// prepare query statement
$stmt = $this->conn->prepare($query2);
// bind values
$stmt->bindParam(1, $this->title);
$stmt->bindParam(2, $this->body);
$stmt->bindParam(3, $this->class_event);
$stmt->bindParam(4, $this->start);
$stmt->bindParam(5, $this->end);
$stmt->bindParam(6, $this->case_id);
$stmt->bindParam(7, $this->worker_id);
// execute the query
$stmt->execute();
$this->conn->commit();
return true;
} catch (Exception $e) {
$stmt->rollBack();
return false;
}
}
The two inserts works perfectly but my problem is that the two ids for each table are not the same and as a consequence I can not delete at the same time an specific record from both tables and I don't know how to do it. I read about Cascade and other possible solutions but none of them seem pausible for my problem. I don't mind to create another column to use it as reference for both tables but I don't know how to do it in the above query.
Thank you in advance
Last insert id is $this->conn->insert_id;
You can get it after the operation and use the identifier.
For example to add it to the desired table

MySQLi: How to insert into multiple tables with prepared statements

I am in a situation where I need to insert into 2 tables in a query. I've searched around web and could not find solution. What I want to do is insert values in user table & insert values in profile simultaneously. I could do one after the other way but I've read that it is not efficient and is considered as poor coding technique.
Current Code:
$statement = $db->prepare("
BEGIN;
INSERT INTO `user`(`username`, `email`, `password_hashed`, `fname`, `lname`, `dob`, `agreement`, `gender`, `access_token`)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);
INSERT INTO `profile_picture`(`owner`) VALUES (LAST_INSERT_ID());
COMMIT;
");
if($statement) {
$statement->bind_param("ssssssiss", $username, $email, $hashedPassword, $fname, $lname, $dob, $agreement, $gender, $access_token);
$statement->execute();
$statement->close();
echo "DONE";
exit();
}
else printf("Error: %s.\n", $db->error);
I had issues with this trying to copy answers like Frank's. The proper way to do it is:
<?php
try {
$db->beginTransaction();
$stmt = $db->prepare("QUERY");
$stmt->execute();
$stmt = $db->prepare("ANOTHER QUERY??");
$stmt->execute();
$db->commit();
}
catch(PDOException $ex) {
//Something went wrong rollback!
$db->rollBack();
echo $ex->getMessage();
}
After the first statement is executed, you can then gain access to the insertID from PHP using the following: $last_id = $db->lastInsertId();
Hope this helps!
Try using mysqli_multi_query, Check this link for example http://blog.ulf-wendel.de/2011/using-mysql-multiple-statements-with-php-mysqli/
Maybe this one can help you: MySQL Insert into multiple tables?
I think you need a statement like this:
BEGIN;
INSERT INTO user(column_a,column_b) VALUES('value_a','value b');
INSERT INTO profile(column_x,column_y) VALUES('value_x','value_y');
COMMIT;
If you need the last id from user table, you can use the LAST_INSERT_ID() function.

Mysqli INSERT with $_POST

I have been ripping my hair for days over this problem so any helpful advice would be appreciated. Calling the following function returns nothing. The POST values are set (They print with echo) and the database let me update and extract with other functions. What am i missing?
Oh yea, all the values are strings.
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)");
$stmt->bind_param("sss", $_POST['name'], $_POST['layout'], $_POST['page_id']);
$stmt->execute();
$stmt->close();
At glance, there is nothing wrong with this code (in case you are indeed using mysqli). So, the only way to get to know what is going wrong is to get the error message.
Add this line before connect
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and make sure you can see PHP errors
Try this
$sql = "INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)";
if (!$stmt = $db->prepare($sql)) {
die($db->error);
}
$stmt->bind_param("ssi", $_POST['name'], $_POST['layout'], $_POST['page_id']);
if (!$stmt->execute()) {
die($stmt->error);
}
$stmt->close();
Or, if, as you said, all your values are strings (given, they are as well defined as varchars/something similar in your database), you can still bind_param("sss"...
Aren't page_id's integers ? Since the asker first tagged the question as PDO, here is the PDO version :
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (:name,:layout,:pid)");
$sth->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$sth->bindParam(':layout', $_POST['layout'], PDO::PARAM_STR);
$sth->bindParam(':pid', $_POST['page_id'], PDO::PARAM_INT);
$stmt->execute();
Or (MySQLi):
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)");
$stmt->bind_param("ssi", $_POST['name'], $_POST['layout'], $_POST['page_id']);
$stmt->execute();
Or (PDO) :
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES (?,?,?)");
$stmt->execute(array($_POST['name'], $_POST['layout'], $_POST['page_id']));
Here you are:
$name = $_POST['layout'];
$layout = $_POST['layout'];
$page_id= $_POST['page_id'];
$stmt = $db->prepare("INSERT INTO content_page (name, layout, page_id) VALUES ('".$name."','".$layout."','".$page_id."')");

Insert into 2 tables from 1 form. Mysql Transaction?

The user will create an article and submit an image with it.
+The article will go to the articles table.
+The image will go to images table (so that it can be used in other areas of the site).
It has been suggested I use TRANSACTIONS but I am getting errors.
$sql ='BEGIN INSERT INTO articles(article_title, article_text, article_date)
VALUES (?, ?, NOW())
INSERT INTO images(article_id, image_caption)
VALUES(LAST_INSERT_ID(),?);
COMMIT';
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)) {
$stmt->bind_param('sss', $_POST['article_name'], $_POST['description'], $_POST['image_caption']);
$OK = $stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
$stmt->free_result();
} else{
echo "Failure- article not uploaded";
}
$mysqli->query("START TRANSACTION");
$stmt = $mysqli->prepare('INSERT INTO articles(article_title, article_text, article_date) VALUES (?, ?, NOW())');
$stmt->bind_param('ss', $_POST['article_name'], $_POST['description']);
$stmt->execute();
$stmt = $mysqli->prepare('INSERT INTO images (article_id, image_caption) VALUES(LAST_INSERT_ID(),?)');
$stmt->bind_param('s', $_POST['image_caption']);
$stmt->execute();
$stmt->close();
$mysqli->query("COMMIT");
It looks like you are using PDO (nice!). With PDO, you can get your transactions in an easy way with beginTransaction() and commit()
Your code would look like:
$pdo->beginTransaction();
// .. fire your 'normal' queries.
// .. and yet some more queries
$pdo->commit();
Then, I'd personally write separate INSERT queries in just two separate statements. More readable in my opinion.
Example:
$pdo->beginTransaction();
$first = $pdo->prepare('INSERT INTO table (field, otherField) VALUES(?,?)');
$second = $pdo->prepare('INSERT INTO table (field, otherField) VALUES(?,?)');
$first->execute(array( .. your data (values) .. ));
$second->execute(array( .. your data (values) .. ));
$pdo->commit();
$sql ='START TRANSACTION;
INSERT INTO articles (article_id,article_title, article_text, article_date) VALUES (NULL,?, ?, NOW());
INSERT INTO images (article_id, image_caption) VALUES(LAST_INSERT_ID(),?);
COMMIT;';

Proper way to pass query data to methods?

I have a User class and I'm wondering what would be the "most recommended" way to handle insertions?
Option 1: Use an existing object
// insert a new user and return the user id
public function insert() {
$sql = "INSERT INTO users (username, password, email, avatar, subscribe, created, last_login, valid) VALUES
(?, ?, ?, ?, ?, ?, ?, ?)";
$sth = $this->db->prepare($sql);
$sth->bindParam(1, $this->username, PDO::PARAM_STR);
$sth->bindParam(2, $this->password, PDO::PARAM_STR);
$sth->bindParam(3, $this->email, PDO::PARAM_STR);
$sth->bindParam(4, $this->avatar, PDO::PARAM_STR);
$sth->bindParam(5, $this->subscribe, PDO::PARAM_STR);
$sth->bindParam(6, $this->created, PDO::PARAM_STR);
$sth->bindParam(7, $this->last_login, PDO::PARAM_STR);
$sth->bindParam(8, $this->valid, PDO::PARAM_STR);
$sth->execute();
return $this->db->lastInsertId();
}
Option 2: Pass the information in as an array
// insert a new user and return the user id
public function insert(array $fields = array()) {
if(!empty($fields)) {
$sql = "INSERT INTO users (username, password, email, avatar, subscribe, created, last_login, valid) VALUES
(:username, :password, :email, :avatar, :subscribe, :created, :last_login, :valid)";
$sth = $this->db->prepare($sql);
$sth->execute($fields);
return $this->db->lastInsertId();
}
}
Another option? Does it make any difference?
Both ways are okay but personally I suggest second option

Categories