How to run multiple queries based on IF conditions? [duplicate] - php

I am trying to write prepared statement for user input. parameter numbers are variable depends on user input. Oam trying this code
PHP code:
$string = "my name";
$search_exploded = explode( " ", $string );
$num = count( $search_exploded );
$cart = array();
for ( $i = 1; $i <= $num; $i ++ ) {
$cart[] = 's';
}
$str = implode( '', $cart );
$inputArray[] = &$str;
$j = count( $search_exploded );
for ( $i = 0; $i < $j; $i ++ ) {
$inputArray[] = &$search_exploded[ $i ];
}
print_r( $inputArray );
foreach ( $search_exploded as $search_each ) {
$x ++;
if ( $x == 1 ) {
$construct .= "name LIKE %?%";
} else {
$construct .= " or name LIKE %?%";
}
}
$query = "SELECT * FROM info WHERE $construct";
$stmt = mysqli_prepare( $conn, $query );
call_user_func_array( array( $stmt, 'bind_param' ), $inputArray );
if ( mysqli_stmt_execute( $stmt ) ) {
$result = mysqli_stmt_get_result( $stmt );
if ( mysqli_num_rows( $result ) > 0 ) {
echo $foundnum = mysqli_num_rows( $result );
while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) {
echo $id = $row['id'];
echo $name = $row['name'];
}
}
}
When I print_r($inputArray), the output is:
Array ( [0] => ss [1] => my [2] => name )
There is no error showing in error log.
What is wrong?

The % wrapping goes around the parameters, not the placeholders.
My snippet will be using object-oriented mysqli syntax instead of the procedural syntax that your code demonstrates.
First you need to set up the necessary ingredients:
the WHERE clause expressions -- to be separated by ORs
the data types of your values -- your values are strings, so use "s"
the parameters to be bound to the prepared statement
I am going to combine #2 and #3 into one variable for simpler "unpacking" with the splat operator (...). The data type string must be the first element, then one or more elements will represent the bound values.
As a logical inclusion, if you have no conditions in your WHERE clause, there is no benefit to using a prepared statement; just directly query the table.
Code: (100% Tested / Successful Code)
$string = "my name";
$conditions = [];
$parameters = [''];
foreach (array_unique(explode(' ', $string)) as $value) {
$conditions[] = "name LIKE ?";
$parameters[0] .= 's';
$parameters[] = "%{$value}%";
}
// $parameters now holds ['ss', '%my%', '%name%']
$query = "SELECT * FROM info";
if ($conditions) {
$stmt = $conn->prepare($query . ' WHERE ' . implode(' OR ', $conditions));
$stmt->bind_param(...$parameters);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = $conn->query($query);
}
foreach ($result as $row) {
echo "<div>{$row['name']} and whatever other columns you want</div>";
}
For anyone looking for similar dynamic querying techniques:
SELECT with dynamic number of values in IN()
INSERT dynamic number of rows with one execute() call

Write a generic query handler and pass it your query, the array of parameters, and the list of parameter types. Get back an array of results or messages. Here's my own personal version for mysqli (I mostly use PDO, but have a similar function set up for that as well). Do the same for inserts, updates, and deletes. Then simply maintain your one library and use it for everything you do :) Note that if you start with this, you'll probably want to do a better job of dealing with connection errors, etc.
<?php
// this is normally in an include() file
function getDBConnection(){
// your DB credentials
$hostname="127.0.0.1";
$username="ausername";
$password="supersecret";
$database="some_db_name";
$con = new mysqli($hostname, $username,$password, $database);
if($con->connect_error) {
return false;
}
return $con;
}
// generic select function.
// takes a query string, an array of parameters, and a string of
// parameter types
// returns an array -
// if $retVal[0] is true, query was successful and returned data
// and $revVal[1...N] contain the results as an associative array
// if $retVal[0] is false, then $retVal[1] either contains the
// message "no records returned" OR it contains a mysql error message
function selectFromDB($query,$params,$paramtypes){
// intitial return;
$retVal[0]=false;
// establish connection
$con = getDBConnection();
if(!$con){
die("db connection error");
exit;
}
// sets up a prepared statement
$stmnt=$con->prepare($query);
$stmnt->bind_param($paramtypes, ...$params);
$stmnt->execute();
// get our results
$result=$stmnt->get_result()->fetch_all(MYSQLI_ASSOC);
if(!$result){
$retVal[1]="No records returned";
}else{
$retVal[0]=true;
for($i=0;$i<count($result);$i++){
$retVal[]=$result[$i];
}
}
// close the connection
$con->close();
return $retVal;
}
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
// our query, using ? as positional placeholders for our parameters
$q="SELECT useridnum,username FROM users WHERE username=? and password=?";
// our parameters as an array -
$p=array($myusername,$mypassword);
// what data types are our params? both strings in this case
$ps="ss";
// run query and get results
$result=selectFromDB($q,$p,$ps);
// no matching record OR a query error
if(!$result[0]){
if($result[1]=="no records returned"){
// no records
// do stuff
}else{
// query error
die($result[1]);
exit;
}
}else{ // we have matches!
for($i=1;$i<count($result);$i++){
foreach($result[$i] as $key->$val){
print("key:".$key." -> value:".$val);
}
}
}
?>

Related

I am not getting the :placeholder to change in my PHP scripting? [duplicate]

I am trying to write prepared statement for user input. parameter numbers are variable depends on user input. Oam trying this code
PHP code:
$string = "my name";
$search_exploded = explode( " ", $string );
$num = count( $search_exploded );
$cart = array();
for ( $i = 1; $i <= $num; $i ++ ) {
$cart[] = 's';
}
$str = implode( '', $cart );
$inputArray[] = &$str;
$j = count( $search_exploded );
for ( $i = 0; $i < $j; $i ++ ) {
$inputArray[] = &$search_exploded[ $i ];
}
print_r( $inputArray );
foreach ( $search_exploded as $search_each ) {
$x ++;
if ( $x == 1 ) {
$construct .= "name LIKE %?%";
} else {
$construct .= " or name LIKE %?%";
}
}
$query = "SELECT * FROM info WHERE $construct";
$stmt = mysqli_prepare( $conn, $query );
call_user_func_array( array( $stmt, 'bind_param' ), $inputArray );
if ( mysqli_stmt_execute( $stmt ) ) {
$result = mysqli_stmt_get_result( $stmt );
if ( mysqli_num_rows( $result ) > 0 ) {
echo $foundnum = mysqli_num_rows( $result );
while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) {
echo $id = $row['id'];
echo $name = $row['name'];
}
}
}
When I print_r($inputArray), the output is:
Array ( [0] => ss [1] => my [2] => name )
There is no error showing in error log.
What is wrong?
The % wrapping goes around the parameters, not the placeholders.
My snippet will be using object-oriented mysqli syntax instead of the procedural syntax that your code demonstrates.
First you need to set up the necessary ingredients:
the WHERE clause expressions -- to be separated by ORs
the data types of your values -- your values are strings, so use "s"
the parameters to be bound to the prepared statement
I am going to combine #2 and #3 into one variable for simpler "unpacking" with the splat operator (...). The data type string must be the first element, then one or more elements will represent the bound values.
As a logical inclusion, if you have no conditions in your WHERE clause, there is no benefit to using a prepared statement; just directly query the table.
Code: (100% Tested / Successful Code)
$string = "my name";
$conditions = [];
$parameters = [''];
foreach (array_unique(explode(' ', $string)) as $value) {
$conditions[] = "name LIKE ?";
$parameters[0] .= 's';
$parameters[] = "%{$value}%";
}
// $parameters now holds ['ss', '%my%', '%name%']
$query = "SELECT * FROM info";
if ($conditions) {
$stmt = $conn->prepare($query . ' WHERE ' . implode(' OR ', $conditions));
$stmt->bind_param(...$parameters);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = $conn->query($query);
}
foreach ($result as $row) {
echo "<div>{$row['name']} and whatever other columns you want</div>";
}
For anyone looking for similar dynamic querying techniques:
SELECT with dynamic number of values in IN()
INSERT dynamic number of rows with one execute() call
Write a generic query handler and pass it your query, the array of parameters, and the list of parameter types. Get back an array of results or messages. Here's my own personal version for mysqli (I mostly use PDO, but have a similar function set up for that as well). Do the same for inserts, updates, and deletes. Then simply maintain your one library and use it for everything you do :) Note that if you start with this, you'll probably want to do a better job of dealing with connection errors, etc.
<?php
// this is normally in an include() file
function getDBConnection(){
// your DB credentials
$hostname="127.0.0.1";
$username="ausername";
$password="supersecret";
$database="some_db_name";
$con = new mysqli($hostname, $username,$password, $database);
if($con->connect_error) {
return false;
}
return $con;
}
// generic select function.
// takes a query string, an array of parameters, and a string of
// parameter types
// returns an array -
// if $retVal[0] is true, query was successful and returned data
// and $revVal[1...N] contain the results as an associative array
// if $retVal[0] is false, then $retVal[1] either contains the
// message "no records returned" OR it contains a mysql error message
function selectFromDB($query,$params,$paramtypes){
// intitial return;
$retVal[0]=false;
// establish connection
$con = getDBConnection();
if(!$con){
die("db connection error");
exit;
}
// sets up a prepared statement
$stmnt=$con->prepare($query);
$stmnt->bind_param($paramtypes, ...$params);
$stmnt->execute();
// get our results
$result=$stmnt->get_result()->fetch_all(MYSQLI_ASSOC);
if(!$result){
$retVal[1]="No records returned";
}else{
$retVal[0]=true;
for($i=0;$i<count($result);$i++){
$retVal[]=$result[$i];
}
}
// close the connection
$con->close();
return $retVal;
}
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
// our query, using ? as positional placeholders for our parameters
$q="SELECT useridnum,username FROM users WHERE username=? and password=?";
// our parameters as an array -
$p=array($myusername,$mypassword);
// what data types are our params? both strings in this case
$ps="ss";
// run query and get results
$result=selectFromDB($q,$p,$ps);
// no matching record OR a query error
if(!$result[0]){
if($result[1]=="no records returned"){
// no records
// do stuff
}else{
// query error
die($result[1]);
exit;
}
}else{ // we have matches!
for($i=1;$i<count($result);$i++){
foreach($result[$i] as $key->$val){
print("key:".$key." -> value:".$val);
}
}
}
?>

Why SQL LIKE is only working when the same input is in the database? [duplicate]

I am trying to write prepared statement for user input. parameter numbers are variable depends on user input. Oam trying this code
PHP code:
$string = "my name";
$search_exploded = explode( " ", $string );
$num = count( $search_exploded );
$cart = array();
for ( $i = 1; $i <= $num; $i ++ ) {
$cart[] = 's';
}
$str = implode( '', $cart );
$inputArray[] = &$str;
$j = count( $search_exploded );
for ( $i = 0; $i < $j; $i ++ ) {
$inputArray[] = &$search_exploded[ $i ];
}
print_r( $inputArray );
foreach ( $search_exploded as $search_each ) {
$x ++;
if ( $x == 1 ) {
$construct .= "name LIKE %?%";
} else {
$construct .= " or name LIKE %?%";
}
}
$query = "SELECT * FROM info WHERE $construct";
$stmt = mysqli_prepare( $conn, $query );
call_user_func_array( array( $stmt, 'bind_param' ), $inputArray );
if ( mysqli_stmt_execute( $stmt ) ) {
$result = mysqli_stmt_get_result( $stmt );
if ( mysqli_num_rows( $result ) > 0 ) {
echo $foundnum = mysqli_num_rows( $result );
while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) {
echo $id = $row['id'];
echo $name = $row['name'];
}
}
}
When I print_r($inputArray), the output is:
Array ( [0] => ss [1] => my [2] => name )
There is no error showing in error log.
What is wrong?
The % wrapping goes around the parameters, not the placeholders.
My snippet will be using object-oriented mysqli syntax instead of the procedural syntax that your code demonstrates.
First you need to set up the necessary ingredients:
the WHERE clause expressions -- to be separated by ORs
the data types of your values -- your values are strings, so use "s"
the parameters to be bound to the prepared statement
I am going to combine #2 and #3 into one variable for simpler "unpacking" with the splat operator (...). The data type string must be the first element, then one or more elements will represent the bound values.
As a logical inclusion, if you have no conditions in your WHERE clause, there is no benefit to using a prepared statement; just directly query the table.
Code: (100% Tested / Successful Code)
$string = "my name";
$conditions = [];
$parameters = [''];
foreach (array_unique(explode(' ', $string)) as $value) {
$conditions[] = "name LIKE ?";
$parameters[0] .= 's';
$parameters[] = "%{$value}%";
}
// $parameters now holds ['ss', '%my%', '%name%']
$query = "SELECT * FROM info";
if ($conditions) {
$stmt = $conn->prepare($query . ' WHERE ' . implode(' OR ', $conditions));
$stmt->bind_param(...$parameters);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = $conn->query($query);
}
foreach ($result as $row) {
echo "<div>{$row['name']} and whatever other columns you want</div>";
}
For anyone looking for similar dynamic querying techniques:
SELECT with dynamic number of values in IN()
INSERT dynamic number of rows with one execute() call
Write a generic query handler and pass it your query, the array of parameters, and the list of parameter types. Get back an array of results or messages. Here's my own personal version for mysqli (I mostly use PDO, but have a similar function set up for that as well). Do the same for inserts, updates, and deletes. Then simply maintain your one library and use it for everything you do :) Note that if you start with this, you'll probably want to do a better job of dealing with connection errors, etc.
<?php
// this is normally in an include() file
function getDBConnection(){
// your DB credentials
$hostname="127.0.0.1";
$username="ausername";
$password="supersecret";
$database="some_db_name";
$con = new mysqli($hostname, $username,$password, $database);
if($con->connect_error) {
return false;
}
return $con;
}
// generic select function.
// takes a query string, an array of parameters, and a string of
// parameter types
// returns an array -
// if $retVal[0] is true, query was successful and returned data
// and $revVal[1...N] contain the results as an associative array
// if $retVal[0] is false, then $retVal[1] either contains the
// message "no records returned" OR it contains a mysql error message
function selectFromDB($query,$params,$paramtypes){
// intitial return;
$retVal[0]=false;
// establish connection
$con = getDBConnection();
if(!$con){
die("db connection error");
exit;
}
// sets up a prepared statement
$stmnt=$con->prepare($query);
$stmnt->bind_param($paramtypes, ...$params);
$stmnt->execute();
// get our results
$result=$stmnt->get_result()->fetch_all(MYSQLI_ASSOC);
if(!$result){
$retVal[1]="No records returned";
}else{
$retVal[0]=true;
for($i=0;$i<count($result);$i++){
$retVal[]=$result[$i];
}
}
// close the connection
$con->close();
return $retVal;
}
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
// our query, using ? as positional placeholders for our parameters
$q="SELECT useridnum,username FROM users WHERE username=? and password=?";
// our parameters as an array -
$p=array($myusername,$mypassword);
// what data types are our params? both strings in this case
$ps="ss";
// run query and get results
$result=selectFromDB($q,$p,$ps);
// no matching record OR a query error
if(!$result[0]){
if($result[1]=="no records returned"){
// no records
// do stuff
}else{
// query error
die($result[1]);
exit;
}
}else{ // we have matches!
for($i=1;$i<count($result);$i++){
foreach($result[$i] as $key->$val){
print("key:".$key." -> value:".$val);
}
}
}
?>

You have a form that uses sql Prepared Statements it has over 170+ values, what do you do? [duplicate]

I am trying to write prepared statement for user input. parameter numbers are variable depends on user input. Oam trying this code
PHP code:
$string = "my name";
$search_exploded = explode( " ", $string );
$num = count( $search_exploded );
$cart = array();
for ( $i = 1; $i <= $num; $i ++ ) {
$cart[] = 's';
}
$str = implode( '', $cart );
$inputArray[] = &$str;
$j = count( $search_exploded );
for ( $i = 0; $i < $j; $i ++ ) {
$inputArray[] = &$search_exploded[ $i ];
}
print_r( $inputArray );
foreach ( $search_exploded as $search_each ) {
$x ++;
if ( $x == 1 ) {
$construct .= "name LIKE %?%";
} else {
$construct .= " or name LIKE %?%";
}
}
$query = "SELECT * FROM info WHERE $construct";
$stmt = mysqli_prepare( $conn, $query );
call_user_func_array( array( $stmt, 'bind_param' ), $inputArray );
if ( mysqli_stmt_execute( $stmt ) ) {
$result = mysqli_stmt_get_result( $stmt );
if ( mysqli_num_rows( $result ) > 0 ) {
echo $foundnum = mysqli_num_rows( $result );
while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) {
echo $id = $row['id'];
echo $name = $row['name'];
}
}
}
When I print_r($inputArray), the output is:
Array ( [0] => ss [1] => my [2] => name )
There is no error showing in error log.
What is wrong?
The % wrapping goes around the parameters, not the placeholders.
My snippet will be using object-oriented mysqli syntax instead of the procedural syntax that your code demonstrates.
First you need to set up the necessary ingredients:
the WHERE clause expressions -- to be separated by ORs
the data types of your values -- your values are strings, so use "s"
the parameters to be bound to the prepared statement
I am going to combine #2 and #3 into one variable for simpler "unpacking" with the splat operator (...). The data type string must be the first element, then one or more elements will represent the bound values.
As a logical inclusion, if you have no conditions in your WHERE clause, there is no benefit to using a prepared statement; just directly query the table.
Code: (100% Tested / Successful Code)
$string = "my name";
$conditions = [];
$parameters = [''];
foreach (array_unique(explode(' ', $string)) as $value) {
$conditions[] = "name LIKE ?";
$parameters[0] .= 's';
$parameters[] = "%{$value}%";
}
// $parameters now holds ['ss', '%my%', '%name%']
$query = "SELECT * FROM info";
if ($conditions) {
$stmt = $conn->prepare($query . ' WHERE ' . implode(' OR ', $conditions));
$stmt->bind_param(...$parameters);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = $conn->query($query);
}
foreach ($result as $row) {
echo "<div>{$row['name']} and whatever other columns you want</div>";
}
For anyone looking for similar dynamic querying techniques:
SELECT with dynamic number of values in IN()
INSERT dynamic number of rows with one execute() call
Write a generic query handler and pass it your query, the array of parameters, and the list of parameter types. Get back an array of results or messages. Here's my own personal version for mysqli (I mostly use PDO, but have a similar function set up for that as well). Do the same for inserts, updates, and deletes. Then simply maintain your one library and use it for everything you do :) Note that if you start with this, you'll probably want to do a better job of dealing with connection errors, etc.
<?php
// this is normally in an include() file
function getDBConnection(){
// your DB credentials
$hostname="127.0.0.1";
$username="ausername";
$password="supersecret";
$database="some_db_name";
$con = new mysqli($hostname, $username,$password, $database);
if($con->connect_error) {
return false;
}
return $con;
}
// generic select function.
// takes a query string, an array of parameters, and a string of
// parameter types
// returns an array -
// if $retVal[0] is true, query was successful and returned data
// and $revVal[1...N] contain the results as an associative array
// if $retVal[0] is false, then $retVal[1] either contains the
// message "no records returned" OR it contains a mysql error message
function selectFromDB($query,$params,$paramtypes){
// intitial return;
$retVal[0]=false;
// establish connection
$con = getDBConnection();
if(!$con){
die("db connection error");
exit;
}
// sets up a prepared statement
$stmnt=$con->prepare($query);
$stmnt->bind_param($paramtypes, ...$params);
$stmnt->execute();
// get our results
$result=$stmnt->get_result()->fetch_all(MYSQLI_ASSOC);
if(!$result){
$retVal[1]="No records returned";
}else{
$retVal[0]=true;
for($i=0;$i<count($result);$i++){
$retVal[]=$result[$i];
}
}
// close the connection
$con->close();
return $retVal;
}
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
// our query, using ? as positional placeholders for our parameters
$q="SELECT useridnum,username FROM users WHERE username=? and password=?";
// our parameters as an array -
$p=array($myusername,$mypassword);
// what data types are our params? both strings in this case
$ps="ss";
// run query and get results
$result=selectFromDB($q,$p,$ps);
// no matching record OR a query error
if(!$result[0]){
if($result[1]=="no records returned"){
// no records
// do stuff
}else{
// query error
die($result[1]);
exit;
}
}else{ // we have matches!
for($i=1;$i<count($result);$i++){
foreach($result[$i] as $key->$val){
print("key:".$key." -> value:".$val);
}
}
}
?>

mysqli bind_param number of elements in type doesn't match bind variables [duplicate]

I am trying to write prepared statement for user input. parameter numbers are variable depends on user input. Oam trying this code
PHP code:
$string = "my name";
$search_exploded = explode( " ", $string );
$num = count( $search_exploded );
$cart = array();
for ( $i = 1; $i <= $num; $i ++ ) {
$cart[] = 's';
}
$str = implode( '', $cart );
$inputArray[] = &$str;
$j = count( $search_exploded );
for ( $i = 0; $i < $j; $i ++ ) {
$inputArray[] = &$search_exploded[ $i ];
}
print_r( $inputArray );
foreach ( $search_exploded as $search_each ) {
$x ++;
if ( $x == 1 ) {
$construct .= "name LIKE %?%";
} else {
$construct .= " or name LIKE %?%";
}
}
$query = "SELECT * FROM info WHERE $construct";
$stmt = mysqli_prepare( $conn, $query );
call_user_func_array( array( $stmt, 'bind_param' ), $inputArray );
if ( mysqli_stmt_execute( $stmt ) ) {
$result = mysqli_stmt_get_result( $stmt );
if ( mysqli_num_rows( $result ) > 0 ) {
echo $foundnum = mysqli_num_rows( $result );
while( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) {
echo $id = $row['id'];
echo $name = $row['name'];
}
}
}
When I print_r($inputArray), the output is:
Array ( [0] => ss [1] => my [2] => name )
There is no error showing in error log.
What is wrong?
The % wrapping goes around the parameters, not the placeholders.
My snippet will be using object-oriented mysqli syntax instead of the procedural syntax that your code demonstrates.
First you need to set up the necessary ingredients:
the WHERE clause expressions -- to be separated by ORs
the data types of your values -- your values are strings, so use "s"
the parameters to be bound to the prepared statement
I am going to combine #2 and #3 into one variable for simpler "unpacking" with the splat operator (...). The data type string must be the first element, then one or more elements will represent the bound values.
As a logical inclusion, if you have no conditions in your WHERE clause, there is no benefit to using a prepared statement; just directly query the table.
Code: (100% Tested / Successful Code)
$string = "my name";
$conditions = [];
$parameters = [''];
foreach (array_unique(explode(' ', $string)) as $value) {
$conditions[] = "name LIKE ?";
$parameters[0] .= 's';
$parameters[] = "%{$value}%";
}
// $parameters now holds ['ss', '%my%', '%name%']
$query = "SELECT * FROM info";
if ($conditions) {
$stmt = $conn->prepare($query . ' WHERE ' . implode(' OR ', $conditions));
$stmt->bind_param(...$parameters);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = $conn->query($query);
}
foreach ($result as $row) {
echo "<div>{$row['name']} and whatever other columns you want</div>";
}
For anyone looking for similar dynamic querying techniques:
SELECT with dynamic number of values in IN()
INSERT dynamic number of rows with one execute() call
Write a generic query handler and pass it your query, the array of parameters, and the list of parameter types. Get back an array of results or messages. Here's my own personal version for mysqli (I mostly use PDO, but have a similar function set up for that as well). Do the same for inserts, updates, and deletes. Then simply maintain your one library and use it for everything you do :) Note that if you start with this, you'll probably want to do a better job of dealing with connection errors, etc.
<?php
// this is normally in an include() file
function getDBConnection(){
// your DB credentials
$hostname="127.0.0.1";
$username="ausername";
$password="supersecret";
$database="some_db_name";
$con = new mysqli($hostname, $username,$password, $database);
if($con->connect_error) {
return false;
}
return $con;
}
// generic select function.
// takes a query string, an array of parameters, and a string of
// parameter types
// returns an array -
// if $retVal[0] is true, query was successful and returned data
// and $revVal[1...N] contain the results as an associative array
// if $retVal[0] is false, then $retVal[1] either contains the
// message "no records returned" OR it contains a mysql error message
function selectFromDB($query,$params,$paramtypes){
// intitial return;
$retVal[0]=false;
// establish connection
$con = getDBConnection();
if(!$con){
die("db connection error");
exit;
}
// sets up a prepared statement
$stmnt=$con->prepare($query);
$stmnt->bind_param($paramtypes, ...$params);
$stmnt->execute();
// get our results
$result=$stmnt->get_result()->fetch_all(MYSQLI_ASSOC);
if(!$result){
$retVal[1]="No records returned";
}else{
$retVal[0]=true;
for($i=0;$i<count($result);$i++){
$retVal[]=$result[$i];
}
}
// close the connection
$con->close();
return $retVal;
}
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
// our query, using ? as positional placeholders for our parameters
$q="SELECT useridnum,username FROM users WHERE username=? and password=?";
// our parameters as an array -
$p=array($myusername,$mypassword);
// what data types are our params? both strings in this case
$ps="ss";
// run query and get results
$result=selectFromDB($q,$p,$ps);
// no matching record OR a query error
if(!$result[0]){
if($result[1]=="no records returned"){
// no records
// do stuff
}else{
// query error
die($result[1]);
exit;
}
}else{ // we have matches!
for($i=1;$i<count($result);$i++){
foreach($result[$i] as $key->$val){
print("key:".$key." -> value:".$val);
}
}
}
?>

using mysqli to extract custom data

I am using a function in php for all select queries so that i can dynamically retrieve data from my database ..... I just wanted to know that is my code secure and efficient or if their is a better way to do this, if so please point me to the right direction...thanks
class mysql {
private $conn;
function __construct(){
$this->conn= new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if( mysqli_connect_errno() )
{
trigger_error('Error connecting to host. '.$this->connections[$connection_id]->error, E_USER_ERROR);
}
}
function extracting_data($table, $fields,$condition,$order,$limit){
$query="SELECT ".$fields."
FROM ".$table."
WHERE id =".$this->sql_quote($condition)."
ORDER BY ".$order."
LIMIT ".$limit." ";
//echo $query;
if($stmt = $this->conn->prepare($query)) {
$stmt->execute();
$row = array_pad(array(), $stmt->field_count, '');
$params = array();
foreach($row as $k=>$v) {
$params[] = &$row[$k];
}
call_user_func_array(array($stmt,'bind_result'),$params);
$result = array();
while($stmt->fetch()) {
foreach ($row as $b=>$elem) {
$vals[$b]=$row[$b];
}
$result[]=$vals;
}
$stmt->close();
return $result;
}
}
function sql_quote( $value )
{
if( get_magic_quotes_gpc() )
{
$value = stripslashes( $value );
}
//check if this function exists
if( function_exists( "mysql_real_escape_string" ) )
{
$value = mysql_real_escape_string( $value );
}
//for PHP version < 4.3.0 use addslashes
else
{
$value = addslashes( $value );
}
return $value;
}
}
Now to call the function I am using ::>
$connection=New mysql();
$extract=$connection->extracting_data("tablename","id,name,points","$_GET['id']","date desc","0,10");
The function returns a multi-dimensional array in $result and stores it in $extract ,depending on the data I want to extract..
Any improvements or other suggestions would be appreciated ...
Instead of binding the results and having to do loads of looping, you could simply use mysqli::query() and mysqli_result::fetch_all().
if($stmt = $this->conn->query($query)) {
$result = $stmt->fetch_all(MYSQLI_ASSOC);
$stmt->close();
return $result;
}
You would be better off binding your input variables rather than building up an SQL string containing them, but that may not be feasible using your current approach.
Edit
Sorry, I was an idiot and didn't notice that fetch_all() is only in PHP >= 5.3. You can still do this though which is simpler:
if($stmt = $this->conn->query($query)) {
$result = array();
while ($row = $stmt->fetch_assoc()) {
$result[] = $row;
}
$stmt->close();
return $result;
}
You should watch where the parameters for your function come from. If they come from an unreliable source, then it's very insecure.
If someone passes something like 1 ; DROP TABLE tablename ; SELECT * FROM dual WHERE 1 in the $condition parameter, you'll get the Little Bobby Tables scenario.
Your query will look like the following:
SELECT id, name, points
FROM tablename
WHERE id
ORDER BY
DATE DESC
LIMIT 0, 10
The id here will be casted to BOOLEAN, and the query will select all ids except 0 and NULL.
Is it really what you want?
You probably want to change your $condition to 'id = $id' or something like that.
Do you really need this level of abstraction: generating queries from uknown tables with unknown fields but with predefined SELECT / FROM / ORDER BY / LIMIT stucture?

Categories