use PHP to insert multiple columns to MySQL from browser - php

This should be pretty simple, I am just new to PHP...
If I have this..
http://localhost/write_data.php?value=99 and inside the write_data.php is this...
$dbconnect = mysqli_connect($server, $dbusername, $dbpassword);
$dbselect = mysqli_select_db($dbconnect, "plantData_001");
// Prepare the SQL statement
$sqlAddress = "INSERT INTO sensorData (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
mysqli_query($dbconnect, $sqlAddress);
everything works fine and 99 is appended into the data table. But how do I add multiple values? I have a column named id that needs to be called like this...
http://localhost/write_data.php?id=1234567;value=99

Do you want to insert multiple values?
You should accept the new way to pass values by script query param.
Something like that: http://localhost/write_data.php?values=99,100,88,20,44.
Then you should use i.e. explode function to split values into array and would be able to insert multiple rows.
BUT - you should implement also the functionality to secure your input from query param. Please, read about SQL injection and MySQLi - https://stackoverflow.com/a/16282269/8890700

Related

SQL insert with joins and values

This question has kinda been asked already but I couldn't find my answer. I searched a while and found these related questions, but they didn't help me to understand or answer my problem.
SQL Insert Into with Inner Join
T-SQL INSERT INTO with LEFT JOIN
My question is how to insert data in 2 tables using joins. For example (with php) a user can enter his/her name and the foods he/she likes.
I store them in a variable and an array (the length of the array is not always 3 like below):
$name = "Niels"
$foodsHeLikes = array("apple", "pear", "banana");
This is how I want to store them:
USERS:
UserID name
1 Niels
FOODS:
FoodID userID name //userID is linked to UserID in users table
1 1 apple
2 1 pear
3 1 banana
The link to the first question I pasted above has an insert with a join but I don't see anywhere to put the values in like with a normal insert?
The query from that question:
INSERT INTO orders (userid, timestamp)
SELECT o.userid, o.timestamp FROM users u INNER JOIN orders o ON o.userid = u.id
Judging by what's been going on in the comment section, what you're asking is that you would like to have a more optimal query process. Right now you are using two different queries to populate your two tables, and you're wondering whether that could be done more optimally.
First things first, it's not possible to populate TWO different tables with ONE query.
However, what you could do, is use transactions.
The rest of this answer will follow the assumption that you are using PHP as your backend scripting language (as you tagged yourself).
Also, it is not inherently obvious whether you use prepared statements for your queries or not. In the case you don't, I would highly recommend using prepared statements. Otherwise, you're opening yourself up to SQL Injections (SQLI Attacks).
I will proceed by using mysqli prepared statements in this answer.
<?php
// Your input post variables
$name = $_POST['name'];
$foodArray = $_POST['foodArray'];
/*
I'm using a function to handle my queries,
simply because it makes large piles of code easier to read.
I now know that every time the function:
createUserAndFood($name, $foodArray);
is called, that it will populate my user and food table.
That way I don't have to worry about writing all the code multiple times.
*/
function createUserAndFood($name, $foodArray){
// food array values
$foodValues = array_values($foodArray);
// DB variables
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
/*
Stops the query from auto commiting,
I'll explain later, you can "maybe" disregard this.
*/
$conn->autocommit(FALSE);
// Declare the query
$sql = "INSERT INTO userTable(name) VALUES(?)";
// Prepare and bind
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $name);
// Execute the query
$stmt->execute();
// Fetch last inserted id
$lastID = $conn->insert_id;
$sql = "INSERT INTO foodTable(userId, food) VALUES(?, ?)";
$stmt = $conn->prepare($sql);
for($i = 0; $length = count($foodValues) > $i; $i++){
$stmt->bind_param("is", $lastID, $food);
$food = $foodValues[$i];
$stmt->execute();
}
// Commits the query / queries
$conn->commit();
// Close connection
$stmt->close();
$conn->close();
}
?>
Since you wanted to optimize your queries, the general idea that we are using here, is that we are making use of the MySQL function LAST_INSERT_ID(); via PHP and store it into a variable.
Now, this is mainly relevant if you are using auto incremented id's. If you are not, you can disregard this specific logic and use something else. But if you are, then keep reading.
The reason why we are storing the last id into a variable is because we need to use it multiple times (the new user might have more than one favorite food afterall). If you were not to store the last id into a variable, it would instead take the auto incremented value of the second table after the initial insert, which means upon your third insert statement and forward, you would be working with the wrong id.
Now, as I promised to explain, the reason I'm using $conn->autocommit(FALSE); and $conn->commit(); is because you might not want incomplete data sets in your database. Imagine that a user input is happening, but your database crashes in the middle of it all. You'll have incomplete data sets. If this is not really a concern of yours, then you can disregard that.
To simplify what's going on at the MySQL side of things, think of it like this:
BEGIN;
INSERT userTable SET name = '$name';
SET #lastID = LAST_INSERT_ID();
INSERT foodTable SET id = #lastID, food = '$food';
COMMIT;

Insert All Post Data into MySQL Database

The following topic is close to what I'm trying to ask, but it's outdated considering the mysql functions are deprecated in php now and there are prepared statements for preventing sql injection. insert all $_POST data into mysql using PHP?
Basically, I have a huge number of columns in my database that all need to get filled up when I submit this form. The form matches each column with an input field of the same name (the name attribute on the input field is the same as the column name it belongs in. So $_POST['firstName'] goes in the firstName column, and so on).
Is there a way using mysqli or PDO that I could easily just take all my POST data and automatically insert it into the MySQL table without going through each field by hand? I could code them all out using prepared statements, but there are a ton of columns and I'd like to get them done all at once if possible.
This is the beginning of the long version I don't really want to have to complete.
$stmt = $connection->prepare("INSERT INTO area_retreat
(user,firstName,lastName,...etc)
VALUES
(?,?,?,...etc)
ON DUPLICATE KEY UPDATE
user=VALUES(user),
firstName=VALUES(firstName),
lastName=VALUES(lastName),
...etc
");
$stmt->bind_param("sss",
$username,
$_POST['firstName'],
$_POST['lastName']
);
$stmt->execute();
INSERT INTO area_retreat VALUES (?, ?, ...) -- however, you have to match ALL columns as shown in the database.
If you have an auto increment ID, you will need to provide NULL for that column in the proper column order.
To avoid errors you definitely need to store the list of variables one way or another. It could be as simple as an array:
$fields = array('firstName', etc.);
Then you can loop through your array to generate your sql statement dynamically and using named placeholders instead of question marks, you only need to bind them once. You can also store the values in an array and send that array as a parameter to execute():
// start of query
$values = array();
$query = '...';
foreach ($fields as $field)
{
if (isset($_POST[$field]))
{
// add to query
$query .= "...";
// add value to array so that you can feed the array to `execute`
$values[':' . $field] = $_POST[$field];
}
}
// add end of query
$query .= '...';
$stmt->execute($values);
If you want to use the same variables in an ON DUPLICATE KEY UPDATE section, you can do another loop or build an insert section that you can use twice after looping once.

Insert mysql error when parsing a webpage

Hi when ever I want to insert a comment into my database, I sanitize the data by using Mysql Escape String function this however inserts the following verbatim in field. I print the comment and it works fine and show me the text however when ever I sanitize it, it literally inserts the following into my db
mysql_real_escape_string(Comment)
This is my insert statement, The Id inserts correctly however the comment doesn't it just inserts the "mysql_real_escape_string(Comment)" into the field. what can be wrong?
foreach($html->find("div[class=comment]") as $content){
$comment = $content->plaintext;
$username = mysql_real_escape_string($comment);
$querytwo = "insert into Tchild(Tid,Tcomment)values('$id','$username')";
$resulttwo = $db -> Execute($querytwo);
}
If I'm reading the documentation correctly, you should make the call like this:
$db->Execute("insert into Tchild(Tid,Tcomment)values(?, ?)", array($id, $username));
That will account for proper escaping. Having unescaped values in your query string is dangerous and should be avoided whenever possible. As your database layer has support for SQL placeholders like ? you should make full use of those any time you're placing data in your query.
A call to mysql_real_escape_string will not work unless you're using mysql_query. It needs a connection to a MySQL database to function properly.
Since you're using ADODB, what you want is probably $db->qstr(). For example:
$username = $db->qstr($comment, get_magic_quotes_gpc());
See this page for more information: http://phplens.com/lens/adodb/docs-adodb.htm

pdo insert without variables

I'm trying to insert a new record into a table that contains only an auto number primary key using the following code,
$pdo_conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$sqla = "insert into tbl_gen (gen_sk) values (null)";
$qa = $pdo_conn->prepare($sqla);
$qa->execute();
is this the right way to go about it?
running the sql command in mysql workbench does the job, I'm just feeling like maybe I'm using pdo the wrong way.
Prepared statements are intended to be re-used. If you're just doing a simple one-shot query, then use $pdo->exec() instead. This avoids the overhead of preparing the statement, and just simply "does it".
But regardless, there's nothing "wrong" with how you're going about it.

Searching with multiple variables PHP/Mysql

I'm trying to create a search where the column and value are both variables using prepared statements. The query is where I need help.
$column=$_POST['filter'][0][columnName];
$value = trim($_POST['filter'][0][value]);
$stmt = $mysql->prepare("select * from TABLE WHERE $column like '%$value%'");
I want to be able to specify different column and value pairs to use in conjunction with eachother- so that i can search column one for one value and also column two for another value.
thanks!
I don't think PHP's mysql library has prepared statements. Is your $mysql variable actually a mysqli or pdo connection object?
With mysqli, your code would look like this:
$dbconnection = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$stmt = $dbconnection->prepare("select * from TABLE WHERE $column like '%?%'");
$stmt->bind_param('s',$value);
There's no way to bind a parameter for a column name, which means that you're stuck inserting $column directly into your query. Doing that with any value the user passed you in POST is a bit of a security hole. Since it's constrained to be the same as one of your column names, I'd suggest validating it first to make sure it's not set to something different.

Categories