How do I insert a variable into this oci_parse statement - php

I'm creating PHP code for a web form that sends an automated email after submission, I want to add all the form inputs to an Oracle database.
How do add a variable into my oci_parse statement? for example, how do I pass my $name var into this statement?
I have tried researching the documentation as well as different code.
<?php
if (!empty($name) || !empty($studentemail) || !empty($programofstudy) || !empty($enrolledinanonlineprogram)) {
// create new cnnection (Table name is "register" for sql database)
$db = oci_new_connect("someuser", "somepassword", "somehost");
if (!$db) {
echo "connection error check your server config";
}
else {
echo "Connection sucessful";
}
$name = $_POST['name'];
$studentemail = $_POST['studentemail'];
$programofstudy = $_POST['programofstudy'];
$enrolledinanonlineprogram = $_POST['enrolledinanonlineprogram'];
$bodytext = $_POST['bodytext'];
$stid = oci_parse($db, 'SELECT * FROM register');
$stid = oci_parse($db, 'INSERT INTO register (column1) VALUES (12345)');
oci_execute($stid);
echo "we inserted 12345";
}
?>
The code works and "12345" is inserted into a table in the database however I want to pass in a variable into the oci_parse statement, ​not the hardcoded value.

$stid = oci_parse($db, 'INSERT INTO register (column1) VALUES ('.$variable.')');
OR
$stid = oci_parse($db, "INSERT INTO register (column1) VALUES ($variable)");
//notice the double quotes
If an array or object
$stid = oci_parse($db, 'INSERT INTO register (column1) VALUES ('.json_encode($variable).')');

Be aware of SQL injection, do not append values "as is" to SQL code.
Just imagine a situation
$stid = oci_parse($db,
"UPDATE my_password_table SET password = '$user_input_password' WHERE login = '$user_input_login'");
When user put something like ' or 1 = 1 or '' = ' into $user_input_login field, it makes all passwords to be updated.
Do not trust ANY data you get from a user. Even if you know the user is not able to type that text in that field.
So, the less wrong way to add value into a query is to replace all single quotes into double
$stid = oci_parse($db,
'INSERT INTO register (email) VALUES ('
. str_replace("'", "''", $studentemail) . ' )');
But the right way to do that is use [oci_bind_by_name][1] function
First, you declare bind variables by adding : before the name. Next, you bind the variable to that names
$stid = oci_parse($db, 'INSERT INTO register (email) VALUES (:EMAIL)');
oci_bind_array_by_name($stid, 'EMAIL', $studentemail);
oci_execute($stid);
Note, no quotes required to put string variables.
Also, be careful: this function does not assign the value. It sets up a link between the php variable and name in the query. The value of the variable is taken when oci_execute is performed. That means if you update the variable after it was bound but before query executed, the new value will be applied
$stid = oci_parse($db, 'INSERT INTO register (email) VALUES (:EMAIL)');
$studentemal = 'ABC';
oci_bind_array_by_name($stid, 'EMAIL', $studentemail);
$studentemal = 'XYZ';
oci_execute($stid); // XYZ value is inserted

Related

How to compare input from a user php post to a MySQL

I am teaching myself php and MySQL, and right now I have a problem with MySQL.
I want to compare the phone number that the user put in with the phone number in MYSQL, and if it is in MYSQL to not register it again.
My code:
<?php
require_once 'connection/connection.php';
// Variables from HTML to php
$worker_Name = $_POST['workerNameFromHtml']; // worker Name
$worker_City = $_POST['workerCityFromHtml']; // workerCity
$worker_career = $_POST['workerCareerFromHtml']; // worker career
$worker_PhoneNumber = $_POST['workerPhonNumberFromHtml']; // worker Phone Number
$worker_SecondPhoneNumber = $_POST['workerSecondPhoneNumberFromHtml']; // worker Second Phone Number
$submt=$_POST['submitFromHtml'];
if($submt){
$qry = ( "SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'") or die(mysql_error());
$result = $connect->query($qry);
$num = $result->num_rows;
if ($num == 1) {
$here = "INSERT INTO workersTable VALUES('','$worker_Name','$worker_City','$worker_career','$worker_PhoneNumber','$worker_SecondPhoneNumber')";
$query = $connect->query($here);
print "Successfully added!";
}
else {print "This number has already been entered Thank you for your cooperation!";}}
$connect->close();
So far I have not found a solution to this problem.
your biggest problem here is that you are trying to include variables inside of a string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'"
If you want to do it this way, you need to concatenate your variables with your string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '".$worker_PhoneNumber."'"
Keep in mind if you do this you will want to sanitize your variables first to prevent SQL injections. Also, when you INSERT variables, you will actually want to use a prepared statement like this:
"INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
where the 1st set of values are the names of your columns in the database and the second set are your PHP variables you are putting into it.

PHP ~ Column count doesn't match value count at row 1

Am trying to insert into two tables but get this error
Error: INSERT INTO provide_help (amount) VALUES ( 40,000.00) Column count doesn't match value count at row 1`
below is my insert code
<?php
session_start(); {
//Include database connection details
include('../../dbconnect.php');
$amount = strip_tags($_POST['cat']);
$field1amount = $_POST['cat'];
$field2amount = $field1amount + ($field1amount*0.5);
$sql = "INSERT INTO provide_help (amount) VALUES ( $field1amount)";
if (mysqli_query($conn, $sql))
$sql = "INSERT INTO gh (ph_id, amount) VALUES (LAST_INSERT_ID(), $field2amount)";
if (mysqli_query($conn, $sql))
{
$_SESSION['ph'] ="<center><div class='alert alert-success' role='alert'>Request Accepted.</div></center>";
header("location: PH.php");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
but when i do some thing like this it works
$sql = "INSERT INTO provide_help (amount) VALUES ( $field2amount)";
i just change the $field1amount to $field2amount
but i dont want it that way i want to also get the value of $field1amount and insert it
please any help will be appriciated, thanks
The issue is because the number you're passing in has a comma in it and isn't a string. You need to either pass in "40,000.00" or 40000.00. MySQL is interpreting it as two values: 40 and 000.00.
Using prepared statements will alleviate this (and your security issue) because binding will interpret 40,000.00 as a string. A very basic example to get you started would be:
$sql = "INSERT INTO provide_help (amount) VALUES (?)";
$stmt = $mysqli->prepare($sql);
/*
- the "s" below means string
- NOTE you should still validate the $_POST value,
don't just accept whatever is sent through your form -
make sure it matches the format you're expecting at least
or you'll have data validation issues later on
*/
$stmt->bindParam("s", $field1amount);
$stmt->execute($fieldAmount1);
$result = $res->fetch_assoc();

Can't get php insert to work

Sorry, I'm new to php / mysql. I'm trying to change an existing script to take the results and then insert the value into the database.
This is what I've tried. I'm guessing I'm missing something or the syntax is wrong:
// unique reference number is generated.
// check if it exists or not
$query = "SELECT `ID_UNIQUE` FROM `tbl_referrals`
WHERE `ID_UNIQUE`='".$unique_ref."'";
$result = mysql_query($query) or die(mysql_error().' '.$query);
if (mysql_num_rows($result)==0) {
// We've found a unique number. Lets set the $unique_ref_found
// variable to true and exit the while loop
$unique_ref_found = true;
$sql = "INSERT INTO `tbl_referrals` (`ID_UNIQUE`)
VALUES
(`ID_UNIQUE`)";
}
}
echo 'Your reference number is: '.$unique_ref;
Ticks are for identifiers, single quotes are for string values:
$sql = "INSERT INTO `tbl_referrals` (`ID_UNIQUE`)
VALUES
('ID_UNIQUE')";
}

Php pdo insert query

I need to insert encrypted values in mysql table, but when I use traditional pdo method to insert its inserting the data in wrong format. ex: I insert aes_encrypt(value, key) in place of inserting encrypted value its inserting this as string.
Following is the code :
$update = "insert into `$table` $cols values ".$values;
$dbh = $this->pdo->prepare($update);
$dbh->execute($colVals);
$arr = array("col"=>"aes_encrypt ($val, $DBKey)");
I know i am doing it wrong, but not able to find correct way.
You are almost there, here is a simplified version:
<?php
$sql = "insert into `users` (`username`,`password`) values (?, aes_encrypt(?, ?))";
$stmt = $this->pdo->prepare($sql);
// Do not use associative array
// Just set values in the order of the question marks in $sql
// $fill_array[0] = $_POST['username'] gets assigned to first ? mark
// $fill_array[1] = $_POST['password'] gets assigned to second ? mark
// $fill_array[2] = $DBKey gets assigned to third ? mark
$fill_array = array($_POST['username'], $_POST['password'], $DBKey); // Three values for 3 question marks
// Put your array of values into the execute
// MySQL will do all the escaping for you
// Your SQL will be compiled by MySQL itself (not PHP) and render something like this:
// insert into `users` (`username`,`password`) values ('a_username', aes_encrypt('my_password', 'SupersecretDBKey45368857'))
// If any single quotes, backslashes, double-dashes, etc are encountered then they get handled automatically
$stmt->execute($fill_array); // Returns boolean TRUE/FALSE
// Errors?
echo $stmt->errorCode().'<br><br>'; // Five zeros are good like this 00000 but HY001 is a common error
// How many inserted?
echo $stmt->rowCount();
?>
you can try it like this.
$sql = "INSERT INTO $table (col) VALUES (:col1)";
$q = $conn->prepare($sql);
$q->execute(array(':cols' => AES_ENCRYPT($val, $DBKey)));

Creating an "update" page MYSQL/PHP

I'm currently trying to make a page via php which allows the user to update data in my database. I'm experiencing two problems: first when I run my code I get the "Error: Query was empty", however updates were made to the database and this leads me to my second problem. Fields that were left empty (a user doesn't have to enter data into all the fields if they only have one or two things to update) become blank after the updates are made. This is because my current script updates all elements, but is there any way I can have it where if the user leaves an input field blank, nothing gets changed when the database is updated?
Here is my code:
if (isset($_POST['submit'])) {
$id = $_POST['id'];
$lastname = $_POST['lastname'];
$firstname = $_POST['firstname'];
$color = $_POST['color'];
$number = $_POST['number'];
// need id to be filled and need at least one other content type for changes to be made
if (empty($id) || empty($lastname) and empty($firstname) and empty($major) and empty($gpa)) {
echo "<font color='red'>Invalid Submission. Make sure you have an ID and at least one other field filled. </font><br/>";
} else {
// if all the fields are filled (not empty)
// insert data to database
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
// display success message
echo "<font color='blue'>Data updated successfully.</font>";
// Close connection to the database
mysql_close($con);
}
}
To answer your question, you need to catch the query's result and check for errors on that.
$query = mysql_query(/*query*/);
if (!$query)
//error handling
Be sure to read up on SQL injections, as per my comment.
To better help you understand the behavior you were seeing, I will explain to you what was wrong with your code:
mysql_query ("UPDATE students SET lastname = '$lastname', firstname = '$firstname', favoritecolor = '$color', favoritenumber = '$number' WHERE id = '$id'");
That first part was executing a MySQL query, regardless of that fact that you did not assign it's return value to a variable.
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
The second part was attempting to run a query by passing the first parameter $sql which has not been set, and the second parameter $con which also appears to not have been set. The first query you ran executed just fine while the second one could never execute. Your solution:
$result = mysql_query(
"UPDATE students
SET lastname = '$lastname', firstname = '$firstname',
favoritecolor = '$color', favoritenumber = '$number'
WHERE id = '$id'"
);
if (!$result) {
throw new Exception('Error: ' . mysql_error());
// or die() is fine too if that's what you really prefer
}
if (!mysql_query($sql,$con)) Here $sql and $con are not defined. Should you be running mysql_query twice?
Few guesses:
There is no mysql connect function I assume it's called elsewhere
Print out your query string. I've always found explicitly denoting what is a string and what is a variable by 'SELECT * FROM '.%tblvar.';'; to be much more debug friendly.

Categories