Using oci_parse and oci_execute - php

I'm sure this is something very basic but I can't seem to find my error.
I'm trying to execute the following...
$c = db_connect();
$email = addslashes($email);
$sql = "SELECT * FROM RUSER WHERE email LIKE '" . $email . "';";
$query = oci_parse($c, $sql) or die(oci_error($c));
$response = oci_execute($query) or die(oci_error($c));
but I get oci8 statement Warning: oci_execute(): ORA-00911: invalid character in /path/to/file.php on line 67 where line 67 is where $response is assigned.
So that means there is something wrong with $query right? But I can't seem to find what that would be. The raw sql executes fine from the command line. echoing get_resource_type($query) gives a resource id...
What am I doing wrong?

Do NOT include the ; in your SQL. The ; is not part of SQL itself, its used by various SQL clients (e.g. sql*plus) as a delimiter to mark the end of commands to be sent to the server.

The first error is
$c = oci_connect("user","password","host/dbname") // db_connect() is not true
second error is there should not be ";" in the statement
$sql = "SELECT * FROM RUSER WHERE email LIKE '" . $email . "';";
it should be
$sql = "SELECT * FROM RUSER WHERE email LIKE '" . $email . "'";
if you want to compare better user "=" than LIKE

Yes, the semicolon is an issue, but not the only one.
the query is directly injecting the variable string into the sql -- this is a potential point of vulnerability/insecurity.
there is no need for the LIKE comparison if you aren't using any wildcard characters (e.g. %, _) in your value.
Suggested Code:
$stmt = oci_parse($conn, "SELECT * FROM RUSER WHERE email = :email");
oci_bind_by_name($stmt, ":email", $email);
oci_execute($stmt);
$count = oci_fetch_all($stmt, $resultSet, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
// hypothetical outputs:
// $count = 1
// $resultSet = [['id => 3, 'email' => 'example#example.com', ...]]

Related

oci_bind_by_name() returns error

I'm using PHP to query oracle DB and everything works great unless i try to use oci_bind_by_name to replace a variable
$link = oci_connect("user","password","server/service");
$sql = "SELECT name FROM customers WHERE name LIKE '%:name%'";
$query= oci_parse($link, $sql);
$name = "Bruno";
oci_bind_by_name($query, ":name", $name);
$execute = oci_execute($query);
I also tried to escape the quotes like this, but it returns the same error, i assume it's a problem with the wildcards %
$sql = "SELECT name FROM customers WHERE name LIKE \"%:name%\" ";
The error is not specific:
( ! ) Warning: oci_bind_by_name(): in D:\gdrive\www\sites\pulseiras\php\engine.php on line 30
I'd like to use bind by name to avoid sql injection, how can i make it work ?
OCI is inserting the bound variable to your query and ending up with something like this:
SELECT name FROM customers WHERE name LIKE '%'Bruno'%'
Obviously a couple of unnecessary quotes have been added. This happens because a bound variable is treated as a single item.
You need to modify the variable before you bind, so:
$sql = "SELECT name FROM customers WHERE name LIKE :name"; // chars removed.
$query= oci_parse($link, $sql);
$name = "%Bruno%"; // chars added.
oci_bind_by_name($query, ":name", $name);
As usual, the PHP manual has many useful examples.
It's amazing how the brain only seems to start working after posting the question on stackoverflow. It turns out the solution is to isolate the wildcards and concatenating with the variable:
$sql = "SELECT name FROM customers WHERE name LIKE '%' || :name || '%' ";
$name = "Bruno";
oci_bind_by_name($query, ":name", $name);
$execute = oci_execute($query);

Returning a Boolean Value via PDO Query

I am attempting with no success to return a Boolean Value from the following PHP/PDO call back to jQuery/AJAX:
$db = new PDO('mysql:host=' . $dbhost . ';dbname=' . $dbname, $dbuser, $dbpass);
$sql = "SELECT COUNT(*)" .
"FROM bu_users" .
"WHERE user_email = :email";
$stmt = $db->prepare($sql);
$stmt->execute(array(':email' => $_GET[reg_email]));
if(!$stmt){
$result = $stmt->errorInfo();
} else {
$result = $stmt->fetchColumn();
}
print_r($result);
I am outputting my results via console.log but am only receiving empty responses whether the email matches a database row or not. Any help would be appreciated. Thanks.
SQL syntax problems:
$sql = "SELECT COUNT(*)" .
"FROM bu_users" .
^---
"WHERE user_email = :email";
^---
You're lacking spaces at the indicated spots, and your query ends up looking like:
SELECT COUNT(*)FROM bu_usersWHERE user_email = :email;
^^-- ^^--
Don't generate multiline strings like that. It's far too easy to make silly mistakes like this. At least use a HEREDOC:
$sql = <<<EOL
SELECT COUNT(*)
FROM bu_users
WHERE user_email = :email
EOL;
No need for concatentation, automatic multi-line usage, and you can nicely format your SQL as well.
$stmt = $db->prepare("SELECT 1 FROM bu_users WHERE user_email = ?");
$stmt->execute(array($_GET['reg_email']));
echo json_encode((bool)$stmt->fetchColumn());

Unable to concatenate sql in pdo statement [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I currently have a Get varible
$name = $_GET['user'];
and I am trying to add it to my sql statement like so:
$sql = "SELECT * FROM uc_users WHERE user_name = ". $name;
and run
$result = $pdo -> query($sql);
I get an invalid column name. But that doesn't make sense because if I manually put the request like so
$sql = "SELECT * FROM uc_users WHERE user_name = 'jeff'";
I get the column data, just not when I enter it as a get variable. What am I doing wrong. I am relatively new to pdo.
Update:
Now I have the following:
$name = $_GET['user'];
and
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
//run the query and save the data to the $bio variable
$result = $pdo -> query($sql);
$result->bindParam( ":name", $name, PDO::PARAM_STR );
$result->execute();
but I am getting
> SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
> error in your SQL syntax; check the manual that corresponds to your
> MySQL server version for the right syntax to use near ':name' at line
> 1
For your query with the variable to work like the one without the variable, you need to put quotes around the variable, so change your query to this:
$sql = "SELECT * FROM uc_users WHERE user_name = '$name'";
However, this is vulnerable to SQL injection, so what you really want is to use a placeholder, like this:
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
And then prepare it as you have:
$result = $pdo->prepare( $sql );
Next, bind the parameter:
$result->bindParam( ":name", $name, PDO::PARAM_STR );
And lastly, execute it:
$result->execute();
I find this best for my taste while preventing SQL injection:
Edit: As pointed out by #YourCommonSense you should use a safe connection as per these guidelines
// $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = 'SELECT * FROM uc_users WHERE user_name = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
// perhaps you'll need these as well
$count = $result->num_rows;
$row = $result->fetch_assoc();
/* you can also use it for multiple rows results like this
while ($row = $result->fetch_assoc()) {
// code here...
} */
BTW, if you had more parameters e.g.
$sql = 'SELECT * FROM table WHERE id_user = ? AND date = ? AND location = ?'
where first ? is integer and second ? and third ? are string/date/... you would bind them with
$stmt->bind_param('iss', $id_user, $date, $location);
/*
* i - corresponding variable has type integer
* d - corresponding variable has type double
* s - corresponding variable has type string
* b - corresponding variable is a blob and will be sent in packets
*/
Source: php.net
EDIT:
Beware! You cannot concatenate $variables inside bind_param
Instead you concatenate before:
$full_name = $family_name . ' ' . $given_name;
$stmt->bind_param('s', $full_name);
Try this .You didn't put sigle quote against variable.
$sql = "SELECT * FROM uc_users WHERE user_name = '". $name."'";
Note: Try to use Binding method.This is not valid way of fetching data.
$sql = "SELECT * FROM 'uc_users' WHERE user_name = '". $name."' ";

Textareas with dynamically-assigned name throws my code

I have a number of textareas, each with a unique assigned name (name="adcode$ID", for example). When I try to pass those names to the code below, it doesn't work because of the dynamic part.
if (isset($_POST['editadapp'])) { // Edit AD
$newadcode = mysql_real_escape_string($_POST['.adcode$ID.']);
$doedit = "UPDATE ads SET adcode = '".$newadcode."') WHERE ads_ID=$ID" or die(mysql_error());
$updatead = mysql_query($doedit) or die(mysql_error());
header("Location: " . $_SERVER['PHP_SELF']);
How can I resolve this?
There is so much wrong with this that it's frightening.
Firstly,
$doedit = "UPDATE ads SET adcode = '".$newadcode."') WHERE ads_ID=$ID" or die(mysql_error());
That code snippet is wrong on many levels.
The sql syntax is wrong
The sql is formatted with strings from user input (see parameterization of queries here
or die() should not be used here, you're creating a string
Ideally you should have code like:
$dbh = new PDO('connectionstring to connect to your database');
$sql = 'update ads set adcode = ? where ads_id = ?';
$sth = $dbh->prepare($sql);
$sth->execute(array($_POST['adcode' . $ID], $ID));
Other topics:
Are Paramerterized queries necessary in pdo?
prepared queries with pdo
Preventing sql injection in php
You seem to be attempting string concatenation. Here's how to do that correctly:
$newadcode = mysql_real_escape_string($_POST['adcode' . $ID]);
The following line should simply create a string containing your SQL query; you don't execute it until the next line, there is no function call so the or die is out of place. You also mix concatenation with interpolation (variable names within a double quoted string) which is fine but probably not helping you understand your syntax issues, so let's be consistent:
$doedit = "UPDATE ads SET adcode = '" . $newadcode . "' WHERE ads_ID = " . $ID;
you should use array like adcode[<?php echo $ID;?>] at your page where the text area is and a hidden field name=adID[$ID]. At the page where the query executes
$adID = $_POST['adID'];
$newadcode = mysql_real_escape_string($_POST['adcode']);
$N = count($adID);
for($i=0;$N<$i;$i++){
$doedit = mysql_query("UPDATE ads SET adcode = '$newadcode[$i]' WHERE ads_ID=$adID[$i];") or die(mysql_error());

What is the proper syntax for inserting variables into a SELECT statement?

I believe I have a simple syntax problem in my SQL statement. If I run this code, I get an error in the database query.
$user = $_GET['linevar'];
echo $user; // testing - url variable echos correctly
$sql = "SELECT * FROM `userAccounts` WHERE `name` = $user";
$result = mysql_query($sql) or die("Error in db query");
If I replace $user in the $sql string with 'actualName' or a known record in my table, the code works fine. Am I using the $ variable incorrectly in the SQL string?
You need to surround the value that you're getting from $user with quotes, since it's probably not a number:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
Just as a note, you should also read up on SQL injection, since this code is susceptible to it. A fix would be to pass it through mysql_real_escape_string():
$user = mysql_real_escape_string( $_GET['linevar']);
You can also replace your or die(); logic with something a bit more informative to get an error message when something bad happens, like:
or die("Error in db query" . mysql_error());
You need escape the get input, then quote it.
// this is important to prevent sql injection.
$user = mysql_real_escape_string($_GET['linevar']);
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '$user'";
This should work:
$sql = "SELECT * FROM `userAccounts` WHERE `name` = '" . $user . "'";

Categories