Multiple queries in one php script - php

So I am trying to send data entered in a single form to multiple tables using multiple queries but it is not working. I have the connection thing working right and this way it works fine for one query but the problem comes when I try to use multiple tables, like getting data and sending it to multiple tables
What I have done so far is:
$qry= "INSERT INTO register VALUES (DEFAULT, '".$email."', '".$passw."')";
$qry = "INSERT INTO personalinformation VALUES (DEFAULT, '".$name."',
'".$fname."', '".$age."', '".$gender."', '".$cnic."',
'".$mobileno."','".$address."', '".$appearencestatus."')";
Kindly help.
Thank you so much

With PDO you'd do something like:
$stmt = $db->prepare("INSERT INTO register (email, password) VALUES (:email, passw)";
$stmt->execute(array('name' => $name, 'email' => $email))
Once for each query. It's important to always specify the columns you're inserting against, it avoids ambiguity when your schema changes for some reason plus the crufty DEFAULT junk in there.
Try to prepare directly from a string, don't make intermediate variables for this sort of stuff. Those can easily get confused, over-written, and tangled up in your code.

Did you create a database connection? And did you execute the query with mysqli_query ? Try troubleshooting by echoing out the composed query, and copy pasting it in mysql console or in php myadmin.
Here is a sample:
$con = mysqli_connect('hostname', 'username', 'password', 'dbname');
Your queries composition code: Then
mysqli_query($con, $queryvariablename);
--
P.S make sure you use different variable names for different queries or else the second one will overrite the previous one.

Related

SQL, how to get the automated ID from the previous INSERT?

I am using PHP and SQL and trying to insert user data into two tables upon registration. First in the user_table and second into the character_table. I'm using an automatically generating user_id to link the tables and need to get the value of the user_id from the first INSERT (into user_table) then add it to a column in the character_table.
I tried a few methods and here is where I ended ($username, $email, $password and $character are defined above);
$sql = "INSERT INTO
user_table (id, username, email, password)
VALUES ('NULL', '".$username."', '".$email."', '".$password."')
INSERT INTO
character_table (name, id)
VALUES ('".$character."', 'LAST_INSERT_ID()')";"
I want "id" from user_table to match with "id" inserted into character_table.
When I run the above, nothing seems to be happening. Previous attempts I always ended with id = 0. What is the correct way I can get the ID from the first INSERT?
Run your statements seperately. You run your insertion into your user_table, then grab the id then run your insertion into your character_table
You can grab the id using mysql_insert_id after running the insert. Note that on the php webpage detailing the mysql_insert_id function that it is deprecated as is all mysql* functions. Which leads to...
For the love of everything holy don't concatenate your variables directly to your INSERT statement. Switch to mysqli* functions or PDO if you haven't already and use prepared statements (parameterizing the query). If you build an application using mysql it means you are not parameterizing your queries which means you are at a huge risk for a sql injection attack.
If/when you switch over to mysqli or PDO functions you will find an equivalent mysqli_insert_id() (or PDO::lastInsertID()) function

MySQL Transaction - BEGIN Issues

I've never used Transactions before but I want to ensure that when I the data into the database via my HTML Form, that should there be an issue, there is a rollback.
Sounds awesome, but I'm struggling to fully understand the place and use of them in a MySQL Query.
$sql = "BEGIN
/* Insert the user to the WordPress Database */
INSERT INTO wp_users (user_login, user_pass, user_email)
VALUES ('John', 'Doe', 'john#example.com');
/* Insert the user into our Custom Database */
INSERT INTO users (ID, name)
VALUES (LAST_INSERT_ID(), 'John')
COMMIT";
I've edited some of the code to be easier to read, and I know for example the password isn't secure, but am I doing something wrong with the BEGIN & COMMIT functions for the Transaction?
I'm also trying to use Transactions so that I can make full use of the LAST_INSERT_ID() function. This should then allow me to ensure that between both Databases, the user will share the same ID so I can easily call upon their unique data for various website application reasons.
I've found a few things online, but none really provide an easily understood example. What exactly am I doing wrong? Is my implementation terrible, or am I just missing something? Is the LAST_INSERT_ID() going to work like that?
I'd greatly appreciate any help you can offer. Thank you.
You might use PDO for handling transaction in php. Refer here
For last inserted row id. Refer here
Since you are using Mysqli and you want to rollback if any part of the query failed or commit when queries succeed you can do something like shown in the code below:
( also I assume this part is wrong " INSERT INTO users (ID, name)
VALUES (LAST_INSERT_ID(), 'John') " as you probably want to use "UPDATE" )
//just a temporary variable to store eventual error
$query_ok=true;
//start transaction here
$mysqli->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);
$mysqli->query("INSERT INTO wp_users (user_login, user_pass, user_email)
VALUES ('John', 'Doe', 'john#example.com');") ? null : $query_ok=false;
$mysqli->query("UPDATE users SET name ='John' WHERE ID=".$mysqli->insert_id ) ? null : $query_ok=false;
//if $query_ok is still set to true then we commit changes to database otherwise we do rollback
$query_ok ? $mysqli->commit() : $mysqli->rollback();
You can also use procedural style ( mysqli_query, mysqli_insert_id etc )

php: how to insert large form data into mysql

I am trying to insert a data from a form which has about 1990 characters into mysql. How ever the insert is not working. when i var_damp the content of the variable is shows the correct content. When i set it to an empty string the insert works. I have done my research and still can't get ti to work. I am not trying to upload a file. This characters are from a textarea in my form.
Below is the insert code:
if (isset($_POST['val'])) {
$score = $_POST['val'];
$course = $_POST['course'];
$mysqli->query("INSERT INTO `evaluate` (`id`, `course`, `score`) VALUES (Null, '$course', '$score')");
Note: is score column has type TEXT in the database.
This is a common problem because most introductions to mysqli don't cover it right away even when it should be the first thing you learn. Inserting into any database, especially SQL, requires carefully escaping the values you're supplying. The way these are escaped varies depending on the platform, but the good news is that mysqli can handle it for you.
The key is using prepared statements:
$stmt = $mysqli->prepare("INSERT INTO evaluate (course, score) VALUES (?,?)");
$stmt->bind_param('ss', $_POST['course'], $_POST['val']);
$stmt->execute();
Now it's best to enable exceptions so that any errors are not ignored. Once in a while we all make little mistakes that can be a giant pain to track down if there isn't any warning about them. Exceptions make a lot of noise.
If you're just getting started with PHP and databases, you might want to evaluate using PDO which is significantly better than mysqli for a number of reasons, or a higher level database layer like Doctrine or
Propel which make using the database a lot more pleasant.
I have a single quote (') in the text and not escaping it meant that the SQL statement was been interpreted wrongly
The correct way to go, and you must always do this, is:
$score = $mysqli->real_escape_string($_POST['val']);
$course = $mysqli->real_escape_string($_POST['course']);
$mysqli->query("INSERT INTOevaluate(id,course,score)VALUES (Null, '$course', '$score')");

Error when Passing string values from Python request to PHP

What I am Trying to do
What I am attempting to do is, pass values from my python application to my web api where it gets saved to my database.
The problem
The reason why I am posting is because, I can send integers, 1,2,3 to my database from my python and that saves fine. But If I send "test","ape","tree" nothing is placed in the database. (PS, the data type is varchar(6) )
I can also pass string into the database (using post) from the browser and it works.
What have done
I have created my API , database and python script that passes the data around.
Python.
import requests
load={'par':'ape12'} //This doesnt save "ape" to the database
#load={'par':'3'} //This saves "3" to the database
r=requests.post("http://my-server.com/load.php",data=load)
PHP
<?php
//Connect to DB
include ("connectDB.php");
$loadgot=$_POST['load'];
mysqli_query($con,"INSERT INTO detect(l_result)
VALUES ($loadgot)");
mysqli_close($con);
?>
Hoping someone could assist me in this regard.
Thank you
You need to pass a properly formed query to mysql. The value needs to be surrounded by quotes, but also needs to escape any characters which will break out from the quoted environment. In practice, the best solution these days is to use parametrised queries (see example) like:
$stmt = mysqli_prepare($con, "INSERT INTO detect(l_result) VALUES (?)");
mysqli_stmt_bind_param($stmt, $loadgot);
mysqli_stmt_execute($stmt);
Or if you really want to use text query (you really shouldn't), you can do:
$loadgot_safe = mysqli_real_escape_string($con, $loadgot);
mysqli_query($con,"INSERT INTO detect(l_result) VALUES ('$loadgot_safe')");
The reason why you MUST NOT use:
mysqli_query($con, "INSERT INTO detect(l_result) VALUES ('$loadgot')");
is that anyone can submit multiple values - for example value1'), ('value2 will expand to INSERT INTO detect(l_result) VALUES ('value1'), ('value2') - which is definitely not what you want.
Modify the 'ape12' to "'ape12'".
Because, in MySQL we give the query like this
INSERT INTO detect(l_result) VALUES 'Value1';
So pass the values to MySQL with quotes. But no need for the integers.
From #e4c5 comment. Users wont give the quotes while entering the input. So we ensure the query inside the script. So try to changed the code like this
mysqli_query($con,"INSERT INTO detect(l_result) VALUES ('$loadgot')");

get id of last inserted record without using mysql_insert_id()

$sql =
'INSERT INTO customer
(first_name,
last_name,
email,
password,
date_created,
dob,
gender,
customer_type)
VALUES(:first_name,
:last_name,
:email,
:password,
:date_created,
:dob,
:gender,
:customer_type)' . ' SELECT LAST_INSERT_ID()' ;
Can anyone tell me if the syntax is right? I am having problems using mysql_insert_id that is why i am using SELECT LAST_INSERT_ID()
the error message:
mysql_insert_id() [function.mysql-insert-id]: Access denied for user 'ODBC'#'localhost'
It will work if you add the closing ; between the two queries (at least MySQL will accept it, I don't know if PHP will complain). But, as above, it's not very good code and, if you separate it, will be a race condition. Figure out your kinks with mysql_insert_id() and use that like it's designed for.
The SELECT doesn't make sense in the context of the query. Execute a separate query for it.
No, it makes no sense whatever. If you really wanted to do select last_insert_id, you should do it in a separate (indeed, typically the next) statement.
But there's no need to do that as you can do it at the API level. Just call your appropriate function for your API to get the last insert ID instead. There's no need for a separate statement.
Firstly, you need to use a semi-colon to separate two queries, secondly mysql_query won't allow you to execute two queries simultaneously, thirdly the "SELECT LAST_INSERT_ID" might become problematic if you have many concurrent users (collisions may happen). What is your problem with the mysql_insert_id?

Categories