I am losing my mind on this and I could really use some direction. Just trying to learn PDO along with PHP and failing to understand the logic. I keep trying to find something online that shows a good example of the flow for this test attempt and I'm having a real hard time.
Could someone, even if you have to flame the heck out of me (although like anyone, I'd prefer you not), give me some direction on what I'm doing horribly wrong? I'm building this to start my understanding. There's plenty of info on using mysqli but not pdo and it's driving me nuts.
Thanks in advance. Here's the code:
<?php
# connection info to the db
$host = "--shadowed--";
$dbname = "--shadowed--";
$user = "--shadowed--";
$pass = "--shadowed--";
# pdo options/attributes
$opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); // not getting errors
# data source name
$dsn = "mysql:host=$host;dbname=$dbname";
# basic pdo connection (with added option for error handling)
if (isset($_POST['submit'])) {
try {
$DBH = new PDO($dsn, $user, $pass, $opt);
$STH = $DBH->prepare("INSERT INTO data (name,email,phone,detail,cost) VALUES (:name,:email,:phone,:detail,:cost)");
$STH->bindParam(':name', $name);
$STH->bindParam(':email', $email);
$STH->bindParam(':phone', $phone);
$STH->bindParam(':detail', $detail);
$STH->bindParam(':cost', $cost);
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$detail = $_POST['detail'];
$cost = $_POST['cost'];
$STH->execute();
echo $STH; // attempted to echo back the data, but nothing happens
} catch (PDOException $e) {
echo $e->getMessage(); // no errors
}
}
echo '<form method="POST" action="">';
echo '<p>Enter the below information if you want to live:</p>';
echo 'Name: <input type="text" name="name"><br />';
echo 'E-mail: <input type="text" name="email"><br />';
echo 'Phone: <input type="text" name="phone"><br />';
echo 'Order will be generated randomly from class (once built)<br />';
echo 'Description: <input type="text" name="detail"><br />';
echo 'Cost: <input type="text" name="cost"><br />';
echo '<input type="submit" value="Do-It"></form>';
# close the connection
$DBH = null;
?>
------------- Final Code after Resolution Reached -------------
------------- Final Code after Resolution Reached -------------
(still a newb so can't answer my own question currently)
So first off, I didn't come up with this... it's a mix of everyone here really. I appreciate everyone's help and time with this while I try to learn all the missing links from my knowledge.
The main issues seems to be that when I used my original attempt to utilize if (isset($_POST['submit'])), it didn't actually do or send anything. No errors... no database issues... just a bunch of nothing. We removed that to find it was holding back ( ty #Fred ). Although this didn't change how the code works, it became more efficient using #hjpotter92 suggestion. Then we looked how to submit using this single page. I ended up using a mix of #Fred's and #david strachan suggestions as neither was giving me the right reaction, then I added an if/else statement to perform the check and if it passed, run the try/catch.
It's no work of art, but I learned quite a bit and appreciate the help. Also, I think it will be nice to get something out there people can bump into to see a full example. If any of you guys have any additional suggestions, please let me know. Along with learning the base knowledge, I'm also reviewing how to help against sql injection (which may not be fully covered in this test).
#------------------ Working Code ------------------#
# pdo options/attributes
$opt = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION );
# data source name
$dsn = "mysql:host=$host;dbname=$dbname";
# basic pdo connection (with added option for error handling)
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (!$_POST['name'] || !$_POST['email'] || !$_POST['phone'] || !$_POST['detail'] || !$_POST['cost']) {
echo "<p>Please supply all of the data! You may press your back button to attempt again minion!</p>";
exit;
} else {
try {
$DBH = new PDO($dsn, $user, $pass, $opt);
$STH = $DBH->prepare("INSERT INTO data (name,email,phone,detail,cost) VALUES (:name,:email,:phone,:detail,:cost)");
$STH->bindParam(':name', $_POST['name']);
$STH->bindParam(':email', $_POST['email']);
$STH->bindParam(':phone', $_POST['phone']);
$STH->bindParam(':detail', $_POST['detail']);
$STH->bindParam(':cost', $_POST['cost']);
$STH->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
echo "<p>Data submitted successfully</p>";
}
}
echo '<form method="POST" action="">';
echo '<p>Enter the below information if you want to live:</p>';
echo 'Name: <input type="text" name="name"><br />';
echo 'E-mail: <input type="text" name="email"><br />';
echo 'Phone: <input type="text" name="phone"><br />';
echo 'Order will be generated randomly<br />';
echo 'Description: <input type="text" name="detail"><br />';
echo 'Cost: <input type="text" name="cost"><br />';
echo '<input type="submit" value="Do-It"></form>';
# close the connection
$DBH = null;
?>
To check if the request is POST type use $_SERVER['REQUEST_METHOD'] Documentation
// Get POST variables
$name = isset($_POST['name']) ? $_POST['name'] : '';
$name = isset($_POST['email']) ? $_POST['email'] : '';
$name = isset($_POST['phone']) ? $_POST['phone'] : '';
$name = isset($_POST['detail']) ? $_POST['detail'] : '';
$name = isset($_POST['cost']) ? $_POST['cost'] : '';
If($_SERVER['REQUEST_METHOD'] == "POST") {
Try{
Remainder of code
Switch the ordering from the following
$STH->bindParam(':name', $name);
$STH->bindParam(':email', $email);
$STH->bindParam(':phone', $phone);
$STH->bindParam(':detail', $detail);
$STH->bindParam(':cost', $cost);
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$detail = $_POST['detail'];
$cost = $_POST['cost'];
to
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$detail = $_POST['detail'];
$cost = $_POST['cost'];
$STH->bindParam(':name', $name);
$STH->bindParam(':email', $email);
$STH->bindParam(':phone', $phone);
$STH->bindParam(':detail', $detail);
$STH->bindParam(':cost', $cost);
or simply use:
$STH->bindParam(':name', $_POST['name']);
$STH->bindParam(':email', $_POST['email']);
$STH->bindParam(':phone', $_POST['phone']);
$STH->bindParam(':detail', $_POST['detail']);
$STH->bindParam(':cost', $_POST['cost']);
This is not an answer but a form validation function that could be of help.
I'm sure there are multiple ways of achieving this, but it will surely get you started.
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$detail = $_POST['detail'];
$cost = $_POST['cost'];
if (isset($_POST['submit'])) {
if (empty($name) || empty($email) || empty($phone))) || empty($detail))) || empty($cost)) {
// do something
exit;
}
if (!empty($name) || !empty($email) || !empty($phone))) || !empty($detail))) || !empty($cost)) {
// do something else
// for example, write the data in database
exit;
}
}
Why would you let the user send a blank form? Handle the "please supply all of the data" warning on the client side with javascript. Don't allow the form to get past javascript without fulfilling all of the requirements.
Related
I have email contact in PHP and I wanted to add part where it should check if there is actual order ID written in <input> in my table, otherwise, it sends email.
EDIT: added prepared statement $stmt->execute([ ':order' => $order ]);
<?php
if (isset($_POST['submit'])) {
$subject = $_POST['subject'];
$message = $_POST['message'];
$order = $_POST['orderId'];
$mailTo = "mail#mail.com";
if ($order != "") {
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'username', 'password');
$order = $_POST['orderId'];
$stmt = $db->query("SELECT * FROM Orders WHERE OrderID= :order ");
$stmt->execute([ ':order' => $order ]);
if (!$row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo 'No such ID';
}
else {
$txt .= "Query Received!\n\nOrder ID: ".$order."\n\nMessage context: \n\n".$message;
mail($mailTo, $subject, $txt);
}
}
else {
$txt .= "Bug report received!\n\n"."Message context: \n\n".$message;
mail($mailTo, $subject, $txt);
}
}
?>
And my HTML:
<center><form class="query-form" method="post">
<input style="width: 300px;" class="orderId" type="text" name="orderId" placeholder="Order ID. Leave blank if reporting a bug">
<br>
<input required style="width: 300px;" type="text" name="subject" placeholder="Subject">
<br>
<textarea required name="message" placeholder="Query text" style="width: 300px;" maxlength = "700"></textarea>
<br>
<input type="submit" name="submit" placeholder="Send Query">
</form></center>
When I fill up orderId input and on purpose type characters that aren't in my table ("test"), it still sends an email ( while it should echo that there is no such order ID provided in input):
Query Received!
Order ID:
Message context:
Test
But when I leave orderId empty, PHP works just fine and gives me second message, as wanted.
Can you please tell me why it's just going through that code?
Code that fixed my problem was this one
<?php
if (isset($_POST['submit'])) {
$order = $_POST['orderId'];
if ($order != "") {
try {
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$order = $_POST['orderId'];
$stmt = $db->prepare("SELECT * FROM Orders where OrderId = :orderid ");
$stmt->execute([ ':orderid' => $order ]);
if ($stmt->fetch(PDO::FETCH_ASSOC)) {
$subject = $_POST['subject'];
$message = $_POST['message'];
$order = $_POST['orderId'];
$mailTo = "mail#mail.com";
$txt .= "Query Received!\n\nOrder ID: ".$order."\n\nMessage context: \n\n".$message;
mail($mailTo, $subject, $txt);
}
else {
echo "No such ID.";
}
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
else {
$subject = $_POST['subject'];
$message = $_POST['message'];
$order = $_POST['orderId'];
$mailTo = "mail#mail.com";
$txt .= "Report received!\n\n"."Message context: \n\n".$message;
mail($mailTo, $subject, $txt);
}
}
?>
Making code to work
Problem with original code was part if (!$row = $stmt->fetch(PDO::FETCH_ASSOC)). It didn't do the job.
That's why, after executing $stmt->execute([ ':orderid' => $order ]);, needed to fetch data searched in table and then if there is such row fetched, send an email. If there is no such row, give an error "No such ID."
if ($stmt->fetch(PDO::FETCH_ASSOC)) {
$subject = $_POST['subject'];
$message = $_POST['message'];
$order = $_POST['orderId'];
$mailTo = "mail#mail.com";
$txt .= "Query Received!\n\nOrder ID: ".$order."\n\nMessage context: \n\n".$message;
mail($mailTo, $subject, $txt);
}
else {
echo "No such ID.";
}
Also, I have moved part of code that sends email to run separately with all it's variables after doing all the job with searching:
If orderId input is empty or not: if ($order != "")
If orderId input is empty, check if there is actual row in table specified in OrderId input
At the end, used catch, which in coding progress itself helps you to check if code in try works
Read more about prepared statements: https://www.php.net/manual/en/pdo.prepared-statements.php
Read more about PDO connections and connection managing: https://www.php.net/manual/en/pdo.connections.php
Preventing SQL injection
Article How can I prevent SQL injection in PHP?
Using setAttribute() when connecting to database:
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Second, using prepared statements when searching for specified row:
$order = $_POST['orderId'];
$stmt = $db->prepare("SELECT * FROM Orders where OrderId = :orderid ");
$stmt->execute([ ':orderid' => $order ]);
I have a 3 parameters which should append new/update old entries to a custom mysql table. However, I cannot figure out WHY when I press the submit button ... nothing happens (nor do I get any errors). I am at a loss for what to do. I have asked this question before and have modified my code a bit based on other tutorials thinking that was my issue... no luck :(
I understand that there are concerns for mysql injections - presently I'd just like to see it work and if you have suggestions for mitigating injections I am all ears. I am still a novice at mySQL... but learning slowly and understand (minimally) how string variables can be used to create altered queries.
Here is my code;
echo "<p><h5>Change address:</h5>";
//get user id when the login/visit page
$userid = get_current_user_id();
$loop = new WP_Query( $args );
//form start
echo '<form method = "post" action = "'. $_SERVER['PHP_SELF'] .'">';
//dropdown menu for collecting SKU of product
echo '<br><select name="sku">';
echo '<option>-- Select product--</option>';
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo '<option value=' . $product->get_sku() . '>' . $product->get_sku() . ' </option>';
endwhile;
echo '</select>';
//hidden input for userid
echo '<input type="hidden" id="userid" name="userid" value="' . $userid . '">';
//textbox for address
echo '<br><input type="text" value="Insert new address here" id="address" name="address" size="40" />';
//submit button
echo '<br><input type="submit" name="submit">';
echo '</form>';
//write to database
if(isset($_POST['submit'])) {
$user = $_POST['userid'];
$sku = $_POST['sku'];
$address = $_POST['address'];
$con2 = mysqli_connect("IP","user","password","wpdb");
$updateaddress = "REPLACE INTO wp_newaddress(user, sku, address) VALUES($user, $sku, $address)";
$retval = mysqli_query($con2,$updateaddress);
if($retval)
{
echo 'Data Updated';
}else{
echo 'Data Not Updated';
}
mysqli_close($con2);
}
Thanks :)
You need to use prepare and execute with bound parameters to avoid the SQL injection risk.
You need to check for error conditions after every prepare and execute, and output any errors to your error log. You won't see errors if you don't do this.
Of course you should also watch your PHP error log (which is typically the same as your http server error log), but this goes without saying. Every PHP developer should be watching the error log (even though many developers don't know this).
Here's an example:
$user = $_POST['userid'];
$sku = $_POST['sku'];
$address = $_POST['address'];
$con2 = mysqli_connect("IP","user","password","wpdb");
$updateaddress = "REPLACE INTO wp_newaddress (user, sku, address) VALUES (?, ?, ?)";
$stmt = mysqli_prepare($con2,$updateaddress);
if ($stmt) {
mysqli_stmt_bind_param($stmt, 'sss', $user, $sku, $address);
$ok = mysqli_stmt_execute($stmt);
if ($ok) {
echo 'Data Updated';
} else {
echo 'Data Not Updated';
error_log(mysqli_stmt_error($stmt));
}
mysqli_stmt_close($stmt);
} else {
error_log(mysqli_error($con2));
}
mysqli_close($con2);
Also read answers in How can I prevent SQL injection in PHP?
I have been breaking my head around this html/php/mysqli thing and I can't get it to work. I used several echo statements to see what type of error I am facing but nothing shows up when I am trying to post data into my database.
I have used echo $_POST['name of input']; , print_r($_POST); and only on the 1st one I can see my post. So I think it is posting correctly, right?!
I for some strange reason can't find the problem in my code. I have searched for quiet some time on the web but with little to no result.
This is my HTML:
<html>
<head><title>Test2017</title></head>
<body>
<form action="insert.php" method="post">
<table width="400" border="0" cellspacing="10">
<tr>
<td>voornaam:</td>
<td><input type="text" name="voornaam"></td>
</tr>
<tr>
<td>roepnaam</td>
<td><input type="text" name="roepnaam"></td>
</tr>
<tr>
<td>tussenvoegsel</td>
<td><input type="text" name="tussenvoegsel"></td>
</tr>
<tr>
<td>achternaam</td>
<td><input type="text" name="achternaam"></td>
</tr>
<tr>
<td><input type="submit" value="registreren!"></td>
</tr>
</table>
</form>
</body>
</html>
and this my insert.php, and also at the VALUES i have tried "''",'' and "" but non of that worked.
<?php
$connect=mysqli_connect("localhost","root","usbw","test");
//check connection
if (mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
$voornaam= mysqli_real_escape_string($connect, $_POST['voornaam']);
$roepnaam= mysqli_real_escape_string($connect, $_POST['roepnaam']);
$tussenvoegsel= mysqli_real_escape_string($connect, $_POST['tussenvoegsel']);
$achternaam= mysqli_real_escape_string($connect, $_POST['achternaam']);
$sql="INSERT INTO user (voornaam,roepnaam,tussenvoegsel,achternaam) VALUES ('$voornaam','$roepnaam','$tussenvoegsel','$achternaam')";
if (!mysqli_query($connect,$sql)) {
die('Error: ' . mysqli_error($connect));
}
echo "1 record added";
mysqli_close($connect);
?>
You guys are my only help, because I am pulling my hair out for this.
Thank you in advance!
I have typed the HTML code first and I have pasted it everywhere else even in the database. So I would not have a problem like that. It is all lowercase.
I reformatted your original example to use a prepared statement, as this is safer for handling user generated input. I added a try catch around your code to attempt to raise visibility on whatever error you are running into
<?php
// ensure reporting for mysql is on.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
// Subbing out what you had for db connection to illustrate what each
// of those parameters should point to on your local db
$database = new mysqli('host', 'user', 'password', 'db_schema');
// guessing on whether these are strings.
$voornaam = filter_input(INPUT_POST, 'voornaam', FILTER_SANITIZE_STRING);
$roepnaam = filter_input(INPUT_POST, 'roepnaam', FILTER_SANITIZE_STRING);
$tussenvoegsel = filter_input(INPUT_POST, 'tussenvoegsel', FILTER_SANITIZE_STRING);
$achternaam = filter_input(INPUT_POST, 'achternaam', FILTER_SANITIZE_STRING);
// Formatting for readability, parameterized query
$query = "INSERT INTO user (
voornaam,
roepnaam,
tussenvoegsel,
achternaam
) VALUES ( ?, ?, ?, ?)";
// prepare query statement
$stmt = $database->prepare($query);
// bind parameters and types to statement
$stmt->bind_param('ssss', $voornaam, $roepnaam, $tussenvoegsel, $achternaam);
// execute
$stmt->execute();
echo 'Records added: ' . $stmt->affected_rows;
$stmt->close();
$database->close();
} catch (Exception $e) {
// basic print error to screen error handling, not ideal for
// anything other than testing :)
echo $e->getCode() . ' - ' . $e->getMessage();
}
Ok, we have probably totally confused you now, so try this
<?php
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$connect=mysqli_connect("localhost","root","usbw","test");
if (mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
// using 4 ? one for each column value in the query
$sql="INSERT INTO user
(voornaam,roepnaam,tussenvoegsel,achternaam)
VALUES (?,?,?,?)";
$stmt = $connect->prepare($sql);
// pass the actual data for each parameter, in order
// the 'ssss' in this case denotes that all 4 params are strings
// they can be s=string, i=integer,b=blob, d=decimal
$stmt->bind_param('ssss',
$_POST['voornaam'],
$_POST['roepnaam'],
$_POST['tussenvoegsel'],
$_POST['achternaam']
);
$result = $stmt->execute();
if ( $result ) {
echo "1 record added";
} else {
echo $connect->error;
}
}
?>
I'm writing a PHP page that runs on a server and accepts a few POST paramaters and adds them to a server after validating them using REGEX. For some reason, my server (using WAMP server) is showing an empty result set after the code runs successfully and after I'm redirected to the page at the end.
I think it could be my code, but it could also perhaps be the way the server is setup, currently, all my columns are of type "int(11)" and I don't know which type to choose.
<?php
if(isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["pnumber"])){
$name = $_POST["name"];
$number = $_POST["pnumber"];
$email = $_POST["email"];
$db = new PDO("mysql:dbname=daythree", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if( preg_match("/^[0-9]{10}$/", $number) &&
preg_match("/^[A-Za-z]{2,}[\sA-Za-z]*$/", $name) &&
preg_match("/^[A-z0-9_\-]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/", $email)){
$sql = "INSERT INTO daythree ('name', 'email', 'number') VALUES ('. $name .', '. $email. ', '. $number .')";
header("Location: evilmasterminds.php");
die();
}
}
Thanks and apologies for any trouble.
Not tested but as you use PDO perhaps something more like the following - it should at least point you in the right direction.
if(isset($_POST["name"],$_POST["email"],$_POST["pnumber"])){
$name = $_POST["name"];
$number = $_POST["pnumber"];
$email = $_POST["email"];
try{
$db = new PDO("mysql:dbname=daythree", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if( preg_match( "/^[0-9]{10}$/", $number ) &&
preg_match( "/^[A-Za-z]{2,}[\sA-Za-z]*$/", $name ) &&
preg_match( "/^[A-z0-9_\-]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/", $email ) ){
$sql='insert into `daythree` (`name`,`email`,`number`) values (:name,:email,:number);';
$stmt=$db->prepare($sql);
$stmt->execute(array(
':name' => $name,
':email' => $email,
':number' => $number
));
exit( header("Location: evilmasterminds.php") );
}
}catch( PDOException $e ){
exit('Error: '.$e->getMessage());
}
}
As for column types name and email should almost certainly be varchar whilst number could be int depending upon actual format used in the numbers you receive - again a varchar column might be more suitable.
update:
code changed to account for point made by #riggsfolly regarding exceptions
I've been reading and gathering information for 2 days already and I give up. I have no clue why my piece of simple code is not succeeding.
I want to insert data from one form into two tables and YES I know there are exactly same problems described here and there, but as I said I'm familiar with them and also need to ask more questions.
The problem is in my query somewhere, at least this is what I believe it is.
Here it goes:
unset($err);
//Variables
$host = 'my.server.com';
$user = '123';
$pass = 'password';
$dbname = '123';
$err = array();
$error_form = false;
$img = "sth/sth.jpg";
//Connecting to the database using mysqli application programming interface
$con = mysqli_connect($host, $user, $pass, $dbname);
if (!validate()) {
if (!$con) {
echo "Connection failed : <br />" . $new_con->connect_errno . "<br />" . $new_con->connect_error;
exit;
} else {
echo "Connected! <br />";
}
var_dump($name);
echo "<br />";
var_dump($email);
echo "<br />";
var_dump($img);
echo "<br />";
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_query($con,$query));
echo "<br />";
$_POST["name"] = "";
$_POST["email"] = "";
$_POST["story"] = "";
}
//Form validation
function validate() {
global $name, $email, $story, $err, $error_form;
if($_SERVER['REQUEST_METHOD']=="POST") {
if(isset($_POST["name"]) && !empty($_POST["name"])) {
$name = htmlspecialchars($_POST["name"]);
} else {
$err[0] = "Name is missing.";
$error_form = true;
}
if(isset($_POST["email"]) && !empty($_POST["email"])) {
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
$email = htmlspecialchars($_POST["email"]);
} else {
$err[1] = "Email was verified as incorrect.";
$error_form = true;
}
} else {
$err[1] = "Email is missing.";
$error_form = true;
}
if(isset($_POST["story"]) && !empty($_POST["story"])) {
$story = htmlspecialchars($_POST["story"]);
} else {
$err[2] = "Your story does not contain any characters, it can't be submited.";
$error_form = true;
}
}
return $error_form;
}
Everything what confuses me happens here:
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_query($con,$query));
I've tried to SELECT the id FROM the table1 table and SET it as a #value instead of LAST_INSERT_ID(). I've tried to run two queries...many different solutions.
I found out when I dump mysqli_query($con,$query) it gives false every time unless I don't use transaction, so just simple queries, but I need them.
Last thing is should I use PDO instead of mysqli? Why?
and
Why to use mysqli object oriented style instead of procedural one?
Every help is appreciated. I would like more to understand than just to achieve the effect here.
Be aware this is my first post here, but not the first visit.
You can only do one query at a time with mysqli_query Look at mysqli_multi_query()
http://www.w3schools.com/php/func_mysqli_multi_query.asp
$query= "START TRANSACTION;
INSERT INTO `123`.`table1` (`name1`,`name2`)
VALUES ('". $name . "','". $email ."');
INSERT INTO `123`.`table2` (`table1_id`,`name3`,`name4`)
VALUES (LAST_INSERT_ID(),'". $story . "','". $img ."');
COMMIT;";
var_dump(mysqli_multi_query($con,$query));