Insert into with variables php mysql - php

Im having some trouble getting my SQL query to 'insert into' my database, is it allowed to use variables as table name, field name, and values?
Here my code:
$nameOfDBFromA = "vagtplanA" . $_GET["from"];
$flytnedToQ1 = $con->prepare("SELECT * FROM $nameOfDBToA WHERE ansatId='$_GET[ansatId]' ORDER BY id DESC");
$flytnedToQ1->execute();
$flytnedTo1 = $flytnedToQ1->fetch();
$nameOfFieldToA1 = "a" . $_GET["to"] . "1";
$nameOfFieldToA2 = "a" . $_GET["to"] . "2";
$nameOfFieldToA3 = "a" . $_GET["to"] . "3";
$nameOfFieldToA4 = "a" . $_GET["to"] . "4";
$nameOfFieldToA5 = "a" . $_GET["to"] . "5";
$nameOfFieldToA6 = "a" . $_GET["to"] . "6";
$nameOfFieldToA7 = "a" . $_GET["to"] . "7";
$redigeringsTidspunkt = date("j M Y");
$flytnedTA = $con->prepare(
"INSERT INTO $nameOfDBFromA
(ansatId, edit, $nameOfFieldToA1, $nameOfFieldToA2,
$nameOfFieldToA3, $nameOfFieldToA4, $nameOfFieldToA5,
$nameOfFieldToA6, $nameOfFieldToA7)
VALUES($_GET[ansatId], $redigeringsTidspunkt,
$flytnedTo1[$nameOfFieldToA1], $flytnedTo1[$nameOfFieldToA2],
$flytnedTo1[$nameOfFieldToA3], $flytnedTo1[$nameOfFieldToA4],
$flytnedTo1[$nameOfFieldToA5], $flytnedTo1[$nameOfFieldToA6],
$flytnedTo1[$nameOfFieldToA7]) ")
or die(mysql_error());
$flytnedTA->execute();
SOLVED! I just put my arrays into it own variable
$intoVarToA1 = $flytnedTo1[$nameOfFieldToA1];
$intoVarToA2 = $flytnedTo1[$nameOfFieldToA2];
$intoVarToA3 = $flytnedTo1[$nameOfFieldToA3];
$intoVarToA4 = $flytnedTo1[$nameOfFieldToA4];
$intoVarToA5 = $flytnedTo1[$nameOfFieldToA5];
$intoVarToA6 = $flytnedTo1[$nameOfFieldToA6];
$intoVarToA7 = $flytnedTo1[$nameOfFieldToA7];

You shouldn't substitute variables into the query, you should use bind_param() to provide parameter values for the prepared query.
$flytnedTA = $con->prepare(
"INSERT INTO $nameOfDBFromA
(ansatId, edit, $nameOfFieldToA1, $nameOfFieldToA2,
$nameOfFieldToA3, $nameOfFieldToA4, $nameOfFieldToA5,
$nameOfFieldToA6, $nameOfFieldToA7)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?) ")
or die(mysqli_error($con));
$flytnedTA->bind_param("sssssssss", $_GET[ansatId], $redigeringsTidspunkt,
$flytnedTo1[$nameOfFieldToA1], $flytnedTo1[$nameOfFieldToA2],
$flytnedTo1[$nameOfFieldToA3], $flytnedTo1[$nameOfFieldToA4],
$flytnedTo1[$nameOfFieldToA5], $flytnedTo1[$nameOfFieldToA6],
$flytnedTo1[$nameOfFieldToA7]);
$flytnedTA->execute();
You also need to call mysqli_error($con), not mysql_error().

One of your mistakes is when you want to access a value in an array inside of a string, you can't do:
"$flytnedTo1[$nameOfFieldToA1]"
You have to do it like this:
"{$flytnedTo1[$nameOfFieldToA1]}" // use curly brackets

If you have variables like that, you can insert data into db like below in php.
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";

Is not a good practice put _GET or _POST variables directly on query, use mysqli_real_escape_string to clear the value in variable.
The array values are not parsed directly in strings, you must enclose the expression in {}:
For this: " $flytnedTo1[$nameOfFieldToA3] " replace with: "'{$flytnedTo1[$nameOfFieldToA3]}'" , the result value also need to enclosed by '' singlequoes for sql string value.
$flytnedTA = $con->prepare("INSERT INTO $nameOfDBFromA (ansatId, edit, $nameOfFieldToA1, $nameOfFieldToA2, $nameOfFieldToA3,
$nameOfFieldToA4, $nameOfFieldToA5, $nameOfFieldToA6, $nameOfFieldToA7)
VALUES({$_GET['ansatId']}, '$redigeringsTidspunkt', '{$flytnedTo1[$nameOfFieldToA1]}', '{$flytnedTo1[$nameOfFieldToA2]}',
'{$flytnedTo1[$nameOfFieldToA3]}', '{$flytnedTo1[$nameOfFieldToA4]}', '{$flytnedTo1[$nameOfFieldToA5]}',
'{$flytnedTo1[$nameOfFieldToA6]}', '{$flytnedTo1[$nameOfFieldToA7]}') ") or die(mysql_error());

Related

How can I improve this rustic way to insert info in mySQL with PHP?

I would like to know better ways to improve or optimize this rustic way of adding contents to my mySQL database with PHP only if the variables are not empty.
Thanks.
<?php
$fields = "value_1, value_2, value_3, value_4";
$contents = "'$value1','$value2', '$value3', '$value4'";
if(!empty($value5)){
$fields .= ", value_5";
$contents .= ", '$value5'";
}
if(!empty($value6)){
$fields .= ", value_6";
$contents .= ", '$value6'";
}
$add = "INSERT INTO love_table " . "(" . $fields . ")" . "VALUES (" . $contents . ")";
?>
You can refer here for more details on Insert Data Into MySQL Using MySQLi.
//since the values in columns value5 and value6 can be NULL
$value5 = NULL
$value6 = NULL
//or if you want to set it to ""
$value5 = ""
$value6 = ""
// Create connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
/* Prepare an insert statement */
$insert_query = "INSERT INTO love_table (value_1, value_2, value_3, value_4, value_5, value_6) VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($insert_query);
/* Bind the parameters */
$stmt->bind_param("ssssss", $value1, $value2, $value3, $value4, $value5, $value6);
/* Execute the statement */
$stmt->execute();
/* close statement */
$stmt->close();
/* close connection */
$mysqli->close();
and why we should use bind parameters instead of directly using the values in the query (https://use-the-index-luke.com/sql/where-clause/bind-parameters)
Plan A: Leave the NULLs in the list, and have the columns 'default' the the value you want.
Plan B: Change the NULLs on the fly ..., (isset($val5) ? $val5 : 'N/A') , ...
Plan C: Like B, but in SQL, with COALESCE(?, 'N/A').

PHP/mySQL: INSERT INTO is not posting the correct values

I try to insert some values from a form into my database with this code:
<?php
$link = mysqli_connect("myHost", "myUsername", "myPW", "myDB");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$name1 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn1']);
$name2 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn2']);
$name3 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn3']);
$name4 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn4']);
$name5 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn5']);
$name6 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn6']);
// attempt insert query execution
$sql = "INSERT INTO anmeldungen (FR_PM) VALUES ('$name1')";
$sql = "INSERT INTO anmeldungen (SA_AM) VALUES ('$name2')";
$sql = "INSERT INTO anmeldungen (SA_PM) VALUES ('$name3')";
$sql = "INSERT INTO anmeldungen (SO_AM) VALUES ('$name4')";
$sql = "INSERT INTO anmeldungen (SO_PM) VALUES ('$name5')";
$sql = "INSERT INTO anmeldungen (MO_AM) VALUES ('$name6')";
if(mysqli_query($link, $sql)){
echo "Name ", $name1, " erfolgreich eingetragen. Wir freuen uns auf dich!";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
When I submit the form, it's creating a new row, but it's not inserting any values in all of the columns, but the column MO_AM. Is there a fault in my PHP?
Your query should look like:
$sql = "INSERT INTO anmeldungen
(FR_PM,SA_AM,SA_PM,SO_AM,SO_PM,MO_AM)
VALUES ('$name1','$name2','$name3','$name3','$name4','$name5','$name6')";
Are you sure that the $name variables have values?
Your SQL Query should be:
$sql = "INSERT INTO `anmeldungen`(`FR_PM`,`SA_AM`,`SA_PM`,`SO_AM`,`SO_PM`,`MO_AM`)
VALUES ('$name1','$name2','$name3','$name4','$name5','$name6')";
Though you shouldn't be using $variable as the insert you should look to binding these to prevent SQL Injections.
What you did just overwrite the query.You can insert multiple values into the same table.
Change your query:-
EDIT:
If you use multiple lines for the query it should look like this.
Also When you append the variable.
$sql = 'INSERT INTO anmeldungen (FR_PM,SA_AM,SA_PM,...)'
.' VALUES ('.$name1.','.$name2.','. .... .)'
;

Inserting special characters into SQL database from form

I am submitting form values into a database using PHP but I am running into an issue when user's enter special characters such as an apostrophe. For example if someone enters Bill's Pet Supply into organization, there will be an SQL error.
Here is my code:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$organization = $_POST['organization'];
$sql = $conn->prepare("INSERT INTO submissions VALUES (:firstname, :lastname, :email, :organization)");
$sql->bindValue(':firstname', $firstname);
$sql->bindValue(':lastname', $lastname);
$sql->bindValue(':email', $email);
$sql->bindValue(':organization', $organization);
$sql->execute();
}
$conn->close();
How can I change this code so that apostrophes and other special characters will be supported?
Use prepared statements with bind placeholders. Both PDO and mysqli provide support for those.
Your SQL text would look like this:
$sql = "INSERT INTO submissions (firstname, lastname, email, organization)
VALUES (?, ?, ?, ?)";
If you are using mysqli
mysqli_prepare
myslqi_bind_param
myslqi_execute
$sth = $mysqli->prepare($sql);
if(!$sth) {
// handle error
}
$sth->bind_param("ssss", $firstname, $lastname, $email, $organization);
if( $res = $sth->execute() ) {
// process resultset
}
Similar functions available in PDO, but you can use "bind value" instead of "bind param".
If there's some reason you can't use prepared statements with bind placeholders, then at a minimum, you will need to properly escape any potentially unsafe values included in the SQL text.
If you are using mysqli, then generating the SQL text would look something like this:
$sql = "INSERT INTO submissions (firstname, lastname, email, organization)
VALUES ('" . $mysqli->real_escape_string( $firstname )
. "', '" . $mysqli->real_escape_string( $lastname )
. "', '" . $mysqli->real_escape_string( $email )
. "', '" . $mysqli->real_escape_string( $organization )
. "')";
But don't do that. Use a prepared statement with bind placeholders.

PHP Prepared statement insert into database

Does anyone see anything that is wrong with this. It isn't posting to database at all. There is a basic form asking for name and address on the page. But after submitting the form it just goes to a blank page.
Here is my code. There is stuff above this that reaches out to an API to validate the address data and declares the variables. The dedup part of the code is working in case that matters.
if(empty($errorMessage))
{
// Dedupe the entry into the form
$dupesql = "SELECT * FROM formData WHERE (name = '$full_name' AND address = '$primary_number' AND city = '$city_name' AND state = '$state_abbreviation' AND zip = '$zipcode_full' )";
$duperaw = $mysqli->query($dupesql);
if($duperaw->num_rows > 0) {
$dupe .= "$full_name already exists on $primary_number \n";
}
else {
$sql = "INSERT INTO formData(name, address, city, state, zip, date) VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ssssss", $full_name, $primary_number, $city_name, $state_abbreviation, $zipcode_full, $date);
$stmt->execute();
header("location: index.php?success=1");
exit();
}
}
I have also tried using a query instead of a prepared statement but this just gives the success message and doesnt post to the DB
$sql = "INSERT INTO fromData (name, address, city, state, zip, date) VALUES (".
$full_name . ", " .
$primary_number . ", " .
$city_name . ", " .
$state_abbreviation . ", " .
$zipcode_full . ", " .
$date . ")";
$mysqli->query($sql);
Any help would be great!
Try this SQL
$sql = "INSERT INTO fromData (name, address, city, state, zip, date) VALUES ('$full_name', '$primary_number', '$city_name', '$state_abbreviation', '$zipcode_full', '$date')";
$mysqli->query($sql);
cHao was hinting towards it

How to call a function/method in php to insert function return value to mysql

<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
function random_string($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
if($email)
{
$connect = mysql_connect(" HOST ", " USERNAME ", " PASSWORD") or die("Couldn't Connect");
mysql_select_db("CiniCraftData") or die ("Couldn't Find Database");
$query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', 'random_string(10)')";
$result = mysql_query($query) or die("Some kind of error occured.");
echo ("Welcome " + $username + ", you are now in my database!");
}
else die("You did not fill out the fields correctly, please try again.");
?>
I need help with the line in the middle that starts with $query = "INSER ... 'random_string(10)')";
I need a random alphanumeric string to be inserted into the table called "customers" but instead of calling the function "random_string()" it inserts "random_string(10)" into my table which gives me this for my table with 6 fields:
5 John Smith Jogsz#CiniCraft.com random_string(10) 0
How do I fix this?
$query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', '" . random_string(10) . "')";
This should work!
I think that even though double quotes will parse variables, they wont parse functions.
concatenate the function and your string,
$query = "INSERT INTO customers (fname, lname, email, alphanum) VALUES ('$fname', '$lname', '$email', '" . random_string(10) ."')";
As a sidenote, the query is vulnerable with SQL Injection if the values of the variable came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
make two statements of it. In the first statement you call your function and assign the value to a variable and then in your INSERT... statement you use the variable

Categories