Is this bad practice for inserting data into db? - php

I have this function that inserts data from a checkbox into my sql database and it works just find, but Im pretty new to this so I would like to know if there is a better/safer (from sql injections) way to do this. I know I should be using PDO with prepared statements, but that is something I am tackling later.
Here is the form that produces the html checkboxes:
<form action="" method="post">
<?php
if(empty($clients) === true){
echo '<p>You do not have any clients yet.</p>';
}
else
{
foreach($clients as $client){
echo'
<input type="checkbox" name="client_data[]" value="'.$_SESSION['user_id'].'|'.$class_id.'|'.$client['first_name'].'|'.$client['nickname'].'|'.$client['last_name'].'">
'.$client['first_name'].' ('.$client['nickname'].') '.$client['last_name'].'
<br />';
} // foreach($client
} // if empty
?>
Here is the php that calls the function:
if (isset($_POST['exist_to_class'])){
if (empty($_POST['client_data']) === true){
$errors [] = 'You much select a client to be added to the class.';
} else {
if (isset($_POST['client_data']) && !empty($_POST['client_data']));
foreach ($_POST['client_data'] as $cd){
exist_client_to_class($cd);
header('Location: view_class.php?class_id='.$class_id.' ');
} // foreach $cd
} // else
} //isset
And here is my function that inserts the data into the db:
// add existing client to class ----------------------------------------------------
function exist_client_to_class($cd){
list($user_id, $class_id, $first_name, $last_name, $nickname) = explode('|', $cd);
mysql_query("INSERT INTO `clients` (user_id, class_id, first_name, last_name, nickname, date)
VALUES('$user_id', '$class_id', '$first_name', '$last_name', '$nickname', CURDATE())");
}
First stab at a PDO prepared statement:UPDATE
function exist_client_to_class($cd){
try{
$stmt = $conn->prepare('INSERT INTO clients
(user_id, class_id, first_name, last_name, nickname, date)
VALUES (:user_id, :class_id, :first_name, :last_name, :nickname, CURDATE())
');
list($user_id, $class_id, $first_name, $last_name, $nickname) = explode('|', $cd);
$stmt->execute(array(
':user_id' => $user_id,
':class_id' => $class_id,
':first_name' => $first_name,
':last_name' => $last_name,
':nickname' => $nickname
)
);
}
catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}
Here is the db connect file:
//PDO database connect
try {
$conn = new PDO('mysql:host=localhost;dbname=customn7_cm', '**********', '**********');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}

To put simply, Yes.
You aren't sanitizing or escaping your user data in anyway. you are using the old mysql_* community deprecated functions. You're best bet is to start using PDO or Mysqli
Read this article: PHP Database Access: Are You Doing It Correctly?

This works for most sql injections: (from php.net)
decleration:
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') OR die(mysql_error());
// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
mysql_real_escape_string($user),
mysql_real_escape_string($password));

Related

Redirect page if PDO database update is success

Here is a part of the code I am using to update the database.
It works, but I would like to redirect the user to another page if the database update is a success.
How can I do that ?
I know the header('Location: ../../');, but where to use it ?
$statement = $dbconnect->prepare("
UPDATE members
SET name = :fname, lastname = :lname, phone = :phone
WHERE member_id = :memberid
");
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement->execute(
array(
':fname' => "$fname",
':lname' => "$lname",
':phone' => "$phone",
':memberid' => "$memberid"
)
);
} catch(PDOException $e) {
die("ERROR: Could not connect. " . $e->getMessage());
}
Even tried the following, but no redirection
$statement->execute(array(':fname' => "$fname", ':lname' => "$lname", ':phone' => "$phone",':memberid' => "$memberid"));
if ($statement) {
header('Location: http://sitename.com');
} else {
echo 'It failed!';
}
You need to check the result from the PDOStatement::execute execution and use the correct binding when you execute a prepared statement with an array of insert values (named parameters). Note, that the result from the successful PDO::prepare call is a PDOStatement object, not a boolean value.
The folloling script, based on your code, is a possible solution to your problem:
<?php
try {
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $dbconnect->prepare("
UPDATE members
SET name = :fname, lastname = :lname, phone = :phone
WHERE member_id = :memberid
");
if ($statement === false) {
die("ERROR: Could not prepare statement.");
}
$result = $statement->execute(
array(
':fname' => $fname,
':lname' => $lname,
':phone' => $phone,
':memberid' => $memberid
)
);
if ($result) {
header('Location: http://sitename.com');
exit;
}
} catch(PDOException $e) {
die("ERROR: Could not connect. " . $e->getMessage());
}
?>
If you want to assume that your update was successful as long as you did not encounter any PDO errors (I assume that updates without errors are successful) you can write this:
$statement = $dbconnect->prepare("UPDATE members SET name = :fname, lastname = :lname, phone = :phone WHERE member_id = :memberid");
$dbconnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement->execute(array(':fname' => "$fname", ':lname' => "$lname", ':phone' => "$phone",':memberid' => "$memberid"));
// if there were no errors redirect now
header('Location: ../../');
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
On another note outside of dev you should find a different way to handle the error: this is almost the same as not having a try/catch.

Delete MySQL PHP

mysql_connect('localhost', 'root', '')
or die(mysql_error());
mysql_select_db('shuttle_service_system')
or die(mysql_error());
$insert="INSERT INTO inactive (ID_No, User_Password, First_Name, Last_Name, Email, Contact_Number)
VALUES('". $ID_No ."','". $UserPassword ."','". $FirstName ."','". $LastName ."','". $Email ."','". $ContactNumber ."')";
$result=mysql_query($insert);
$sql="DELETE FROM users WHERE ID_No = '$ID_No'";
$result2=mysql_query($sql);
if($result && $result2){
echo"Successful!";
} else {
echo "&nbsp Error";
}
Hi guys I have been stuck in delete function of MySQL, I have tried searching the net but when I ran my code it always goes to the else part which means there is an error, the insert is already okay but the delete is not.
PHP variables are allowed in double quotes. Hence try this,
$sql="DELETE FROM users WHERE ID_No = $ID_No";
Your first query was not properly escaped. Rewrite like
$insert="INSERT INTO inactive (`ID_No`, `User_Password`, `First_Name`, `Last_Name`, `Email`, `Contact_Number`)
VALUES('$ID_No','$UserPassword','$FirstName','$LastName','$Email','$ContactNumber')";
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. Switching to PreparedStatements is even more better to ward off SQL Injection attacks !
First, use PDO.
Make your connection Database like this:
function connectToDB(){
$host='localhost';
try {
$user = 'username';
$pass = 'password';
$bdd = 'databaseName';
$dns = 'mysql:host='.$host.';dbname='.$bdd.'';
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
return $connexion = new PDO($dns, $user, $pass, $options);
}catch ( Exception $e ) {
echo "Fail to connect: ", $e->getMessage();
die();
}
}
To delete something, here is an example:
function deleteUserWithId($ID_No){
$connexion = connectToDB();
try{
$connexion->exec('DELETE FROM users WHERE ID_No = '.$ID_No);
}catch(Exception $e){
echo "Error: ".$e->getMessage();
}
}
To insert something:
function addInactiveUser($UserPassword,$FirstName ,$LastName ,$Email,$ContactNumber){
$connexion = connectToDB();
$insert = $connexion->prepare('INSERT INTO inactive VALUES(:ID_No,
:User_Password,
:First_Name,
:Last_Name,
:Email,
:Contact_Number
)');
try {
// executing the request
$success = $insert->execute(array(
'ID_No'=>'',
'User_Password'=>$UserPassword,
'First_Name'=>$FirstName ,
'Last_Name'=>$LastName ,
'Email'=>$Email,
'Contact_Number'=>$ContactNumber
));
if($success)
// OK
else
// KO
}
catch (Exception $e){
echo "Error: ".$e->getMessage();
}
}
To make a select:
// If you want to display X user per pages for example
function getAllInactiveUsers($page, $numberInactiveUserPerPage){
$connexion = connectToDB();
$firstInactiveUser = ($page - 1) * $numberInactiveUserPerPage;
$selectAllInactiveUsers = $connexion->prepare('SELECT * FROM inactive ORDER BY ID_No DESC LIMIT '.$firstInactiveUser.','.$numberInactiveUserPerPage);
return $selectAllInactiveUsers ;
}
To get the results of this methods, just do something like this:
$inactiveUsers= getAllInactiveUsers(1,15); // for page 1, display 15 users
$inactiveUsers->execute();
while($row = $inactiveUsers->fetch(PDO::FETCH_OBJ)){
$id = $row->ID_No;
$first_name = $row->First_Name;
// etc...
}
Hope that's help :)
I am not sure if this helps you, but as an alternative you could delete the last entry in the table:
$delQ = mysql_query("SELECT * FROM ph ORDER BY id DESC LIMIT 1" );
while(( $ar = mysql_fetch_array($delQ)) !== false){
mysql_query("DELETE FROM ph WHERE id= $ar[id]");
}

PHP Data Object insert not executing

My PHP form I just changed to use PDO. The only thing I can tell is the execute is not working. Am I supposed to pass something with it?
$db = new PDO('mysql:host=localhost;dbname=x;charset=utf8', 'x', 'x');
if ( !$db )
{
die('Could not connect: ' . mysql_error());
}
$ipaddress = $_SERVER['REMOTE_ADDR'];
$mail = $_POST['mail'];
$stmt = $db->prepare("SELECT * FROM ucm_signup WHERE email =? ");
$stmt->bindValue(1, $mail, PDO::PARAM_STR);
$stmt->execute();
if($stmt->rowCount()== 0) {
//if there are no duplicates...insert
$sql = $db->prepare("INSERT INTO ucm_signup (company, address1, address2, city, province, zip, fname, lname, email, phone, session, iama, buyfrom, group1, ipaddress)
VALUES (:company, :address1, :address2, :city, :province, :zip, :fname, :lname, :mail, :phone, :session, :iama, :buyfrom, :group1, :ipaddress)");
$sql->bindParam(":company", $_POST['company'],PDO::PARAM_STR);
$sql->bindParam(":address1", $_POST['address1'],PDO::PARAM_STR);
$sql->bindParam(":city", $_POST['city'],PDO::PARAM_STR);
$sql->bindParam(":province", $_POST['province'],PDO::PARAM_STR);
$sql->bindParam(":zip", $_POST['zip'],PDO::PARAM_STR);
$sql->bindParam(":fname", $_POST['fname'],PDO::PARAM_STR);
$sql->bindParam(":lname", $_POST['lname'],PDO::PARAM_STR);
$sql->bindParam(":email", $_POST['email'],PDO::PARAM_STR);
$sql->bindParam(":phone", $_POST['phone'],PDO::PARAM_STR);
$sql->bindParam(":session", $_POST['session'],PDO::PARAM_STR);
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR);
$sql->bindParam(":buyfrom", $_POST['buyfrom'],PDO::PARAM_STR);
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR);
$sql->bindParam(":group1", $_POST['group1'],PDO::PARAM_STR);
$sql->bindParam(":ipaddress", $_POST['ipaddress'],PDO::PARAM_STR);
$sql->execute();
}
My database table has no records. Thank you
You are missing some placeholder in your bind parameters, check them carefully
$sql->bindParam(":address1", $_POST['address1'],PDO::PARAM_STR);
$sql->bindParam(":address2", $_POST['city'],PDO::PARAM_STR);
//address2 was missed, probably error is column doesn't match values
$sql->bindParam(":email", $_POST['email'],PDO::PARAM_STR); //supposed to be mail
$sql->bindParam(":imea", $_POST['imea'],PDO::PARAM_STR); //supposed to be iama
You might want to check for pdo errors, here an example taken from manual
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
With this attribute correctly added pdo will notify you if any error occur
PHP users are so PHP users.
First they're laboring on a WALL of code, consists of constantly repeating nearly hundred variables.
Then they get totally lost.
While everything can be done with short and concise code, writing each field name only ONCE
$allowed = array('company', 'address1', 'address2', 'city', 'province',
'zip', 'fname', 'lname', 'email', 'phone', 'session',
'iama', 'buyfrom', 'group1', 'ipaddress');
$_POST['ipaddress'] = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO ucm_signup SET ".pdoSet($allowed, $values);
$stm = $dbh->prepare($sql);
$stm->execute($values);
where pdoSet() helper function can be stored elsewhere and reused for the every insert or update query
function pdoSet($fields, &$values, $source = array()) {
$set = '';
$values = array();
if (!$source) $source = &$_POST;
foreach ($fields as $field) {
if (isset($source[$field])) {
$set.="`".str_replace("`","``",$field)."`". "=:$field, ";
$values[$field] = $source[$field];
}
}
return substr($set, 0, -2);
}

data insertion using PDO

I am new in PDO. I heard that it is more friendly to the programmer to use multiple databases in a project and it is much more secure, so I want to learn PDO. I want to insert data into MySQL using PDO but I can't, and no error message comes. I used the following code:
<?php
class ManageUsers02 {
private $db_con;
public $db_host = "localhost"; // I run this code on my localhost
public $db_name = "todo"; // database name
public $db_user = "root"; // username
public $db_pass = ""; // password
function __construct() {
try {
// connect to database using PDO
$this->db_con = new PDO("mysql:host=$this->db_host;db_name=$this->db_name", $this->db_user, $this->db_pass);
} catch (PDOException $exc) { // PDO exception handling
echo $exc->getMessage();
}
}
public function reg_user($username, $password, $ip_address, $reg_date, $reg_time ) {
try {
// preparing sql query
$query = $this->db_con->prepare("INSERT INTO user_reg (username, password, ip_address, reg_date, reg_time) VALUES ( ?, ?, ?, ?, ? )");
}
catch( PDOException $exc ) { // PDO exception handling
echo $exc->getMessage();
}
try {
// execute sql query
$query->execute(array($username, $password, $ip_address, $reg_date, $reg_time));
}
catch( PDOException $exc ) {
echo $exc->getMessage();
}
$counts = $query->rowCount(); // return value of affected row
// here it should be return 1
echo "<br /> count :: <b> " . $counts . "</b> <br />"; // shows result 0
// no value inserted
}
}
$user_reg = new ManageUsers02();
$user_reg->reg_user('pdo_name', 'pdo_password', '127.0.0.1', '2013-2-6', '4:20 am');
?>
This fails because of insert a string to a mysql Time field.
$sql = "INSERT INTO user_reg ( ... , reg_time) VALUES (..., '4:20 am');
If you want to use '4:20 am' you should use.
TIME( STR_TO_DATE( ? , '%h:%i %p' ))
like
$sql = "INSERT INTO user_reg ( ... , reg_time) VALUES
( ?, ?, ?, ?, TIME( STR_TO_DATE( ? , '%h:%i %p' )))";
and give the class a ok and a counts .
<?php
class ManageUsers02 {
...
public $counts = 0;
public $ok = false;
function __construct() {
try {
$this->db_con = new PDO("mysql:dbname=$this->db_name;host=$this->db_host", $this->db_user, $this->db_pass);
} catch (PDOException $exc) { // PDO exception handling
echo $exc->getMessage();
return;
}
if (!$this->db_con) {
return;
}
$this->ok = true;
}
public function reg_user($username, $password, $ip_address, $reg_date, $reg_time ) {
$this->counts = 0;
$this->ok = false;
$sql = "INSERT INTO user_reg (username, password, ip_address,
reg_date, reg_time) VALUES
( ?, ?, ?, ?, TIME( STR_TO_DATE( ? , '%h:%i %p' )))";
try {
$query = $this->db_con->prepare($sql);
}
catch( PDOException $exc ) { // PDO exception handling
echo $exc->getMessage();
return;
}
if (!$query) {
return;
}
try {
$this->ok = $query->execute(array($username, $password, $ip_address, $reg_date, $reg_time));
}
catch( PDOException $exc ) {
echo $exc->getMessage();
$this->ok = false;
return;
}
if ($this->ok) {
$this->counts = $query->rowCount(); // return value of affected row
}
}
}
$user_reg = new ManageUsers02();
if ($user_reg->ok) {
$user_reg->reg_user('pdo_name4', 'pdo_password4',
'127.0.0.1', '2013-2-6', '04:20 am' );
if ($user_reg->ok) {
echo "<br /> count :: <b> " . $user_reg->counts . "</b> <br />";
} else { echo "Error : Insert failed";}
} else { echo "Error : Connection failed: ";}
?>
+1 to the answer from #moskito-x for spotting the incorrect time format. But there are a couple of other functional problems with your code.
$this->db_con = new PDO("mysql:host=$this->db_host;db_name=$this->db_name", ...
You need to use dbname in the DSN, not db_name. See http://www.php.net/manual/en/ref.pdo-mysql.connection.php
$this->db_con = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", ...
Also you need to enable the error mode like this:
$this->db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
If you don't, PDO doesn't throw exceptions on prepare() or execute(), but those functions just return false if there's an error.
I don't know what's particular problem with your insert, but your implementation is just terrible. By design.
First of all you have to get rid of PDO connection code in the class. You have to create a PDO instance separately, and then only pass it in constructor.
Secondly, you have to get rid of all these try..catch which makes your code bloated with not a slightest benefit.
Also, No class method should ever output a single byte, but return only.
So, it have to be something like
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);
class ManageUsers02
{
private $db_con;
function __construct($db_con)
{
$this->db_con = $db_con;
}
public function reg_user($username, $password, $ip_address, $reg_date, $reg_time )
{
$sql "INSERT INTO user_reg (username, password, ip_address, reg_date, reg_time)
VALUES ( ?, ?, ?, ?, ? )";
$query = $this->db_con->prepare($sql);
$query->execute(array($username, $password, $ip_address, $reg_date, $reg_time));
return $counts = $query->rowCount(); // return value of affected ro
}
}
$user_reg = new ManageUsers02($pdo);
$count = $user_reg->reg_user('pdo_name', 'pdo_password', '127.0.0.1', '2013-2-6', '4:20 am');
var_dump($count);
This setup at least will tell you if something goes wrong.

PHP - for statement in an array

For a PDO execution statement I am trying to make any static information such as column names and array strings to a dynamic array which contains every column from the MySQL table.
The original code was:
$stmt = $conn->prepare("INSERT into data (`username,` `password`, `email`) VALUES username = :username , password = :password , email = :email ");
$stmt->execute(array(
':username' => $entry_username,
':password' => $entry_password,
':email' => $entry_email
));
So far I have been able to change the sql statement to
$sql = "INSERT into DATA (`" . implode('`,`', $columns) . "`) values (:" . implode(',:', $columns) . ")";
$stmt = $conn->prepare($sql);
but have been unable to do a similar thing to the execution array to make it dynamically variating like the statement.
I have tried adding a for statement in the array
for ($i = 0; $i < count($columns); $i++) {
':'.$columns[$i] => ${'entry_'.$columns[$i]};
}
but this hasn't worked.
Any help would be much appreciated.
Thanks in advance!
This is a perfect situation to make good use of a prepared statement.
Try this:
I am kind of assuming what the varuables will be called in the $columns array here.
$stmt = $conn->prepare("INSERT into data
(username, password, email) VALUES( :username , :password, :email )");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
foreach ( $columns as $column ) {
$username = $column['username'];
$password = $column['password'];
$email = $column['email'];
$result = $stmt->execute();
if ( ! $result ) {
// add some error checking code here
}
}
Basically, your code would look like this.
$entry = array(
'username' => $_POST['username'], //assuming it's comming from the post data or for instance $row['username'] if from previous select statement
'password' => $_POST['password'],
'email' => $_POST['email']
);
$sth = $dbh->prepare('INSERT into data (`username,` `password`, `email`) VALUES (:username, :password, :email)');
$sth->bindValue(':username', $entry['username'], PDO::PARAM_INT);
$sth->bindValue(':password', $entry['password'], PDO::PARAM_STR);
$sth->bindValue(':email', $entry['email'], PDO::PARAM_STR);
$sth->execute();
If you want the bound variables to be dynamically created, then you need to create with a loop the bindValue rows:
$entry = array(
'username' => $_POST['username'], //assuming it's comming from the post data or for instance $row['username'] if from previous select statement
'password' => $_POST['password'],
'email' => $_POST['email']
);
$sth = $dbh->prepare('INSERT into data (`username,` `password`, `email`) VALUES (:username, :password, :email)');
foreach($entry as $key => $value) {
$sth->bindValue(':'.$key, $entry[$key], PDO::PARAM_STR);
}
$sth->execute();
or inside the foreach
$sth->bindValue(':'.$key, $value, PDO::PARAM_STR);
Since your keys are (username, password, email) their keynames will be initiated to $key variable, and their values to the $value variable. in the first case it will produce:
$sth->bindValue(':username', $entry['username'], PDO::PARAM_INT);
$sth->bindValue(':password', $entry['password'], PDO::PARAM_STR);
$sth->bindValue(':email', $entry['email'], PDO::PARAM_STR);
Which will be evaluated to:
$sth->bindValue(':username', $_POST['username'], PDO::PARAM_INT);
$sth->bindValue(':password', $_POST['password'], PDO::PARAM_STR);
$sth->bindValue(':email', $_POST['email'], PDO::PARAM_STR);
In the second case it will be directly evaluated.
Have in mind it's completely unacceptable to dynamically create the column names in the query. And you have to reason to do it. However, not a full query is also hard to be read from the other developers. It's enough for you to dynamically create the bound values. You can make a method do it for you. For instance, if you column names in the query are the same way aliased, as the names of the input fields, you will have nothing more to do, but to execute the query.
Let's say you have that helper method:
Class DBConnect {
private $_driver = "mysql";
private $_dbname = "xxxx";
private $_host = "xxxx";
private $_user = "xxxx";
private $_password = "xxxx";
private $_port = 3306;
private $_dbh;
public function __construct($driver = NULL, $dbname = NULL, $host = NULL, $user = NULL, $pass = NULL, $port = NULL) {
$driver = $driver ?: $this->_driver;
$dbname = $dbname ?: $this->_dbname;
$host = $host ?: $this->_host;
$user = $user ?: $this->_user;
$pass = $pass ?: $this->_password;
$port = $port ?: $this->_port;
try {
$this->_dbh = new PDO("$driver:host=$host;port=$port;dbname=$dbname", $user, $pass);
$this->_dbh->exec("set names utf8");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function query($sql) {
$sth = $this->_dbh->prepare($sql);
foreach ($_REQUEST as $key => $value) {
if(is_int($value)) {
$param = PDO::PARAM_INT;
} elseif(is_bool($value)) {
$param = PDO::PARAM_BOOL;
} elseif(is_null($value)) {
$param = PDO::PARAM_NULL;
} elseif(is_string($value)) {
$param = PDO::PARAM_STR;
} else {
$param = FALSE;
}
$sth->bindValue(":$key", $value, $param);
}
$sth->execute();
$result = $sth->fetchAll();
return $result;
}
}
So, lets say in another class you have a lot of queries, separated by methods:
public function getFirstQuery() {
$sql = "SELECT
col1, col2
FROM table1
WHERE col3 = :col3;";
$query = $this->_db->query($sql);
return $query;
}
public function inserSecondquery() {
$sql = "INSERT INTO
`table1`
(col1, col2)
VALUES
((SELECT
id
FROM table2
WHERE col8 = :col8), :post_field_5);";
$query = $this->_db->query($sql);
return $query;
}
Assuming you have called these queries the query() method which also fetches the data, the select one you can foreach to retrieve the data, and the insert one you can just call, to insert data. The only rule here is the post fields should be named same way, for example <input name="post_field_5" />
You can also take a look here: PDO Dynamic Query Building
OK, it seems you need to find library for active record like the ones CodeIgniter uses, or... use CodeIgniter.
From the official documentation:
http://ellislab.com/codeigniter/user-guide/database/helpers.html
$this->db->insert_string();
This function simplifies the process of writing database inserts. It
returns a correctly formatted SQL insert string. Example: $data =
array('name' => $name, 'email' => $email, 'url' => $url);
$str = $this->db->insert_string('table_name', $data);
The first parameter is the table name, the second is an associative
array with the data to be inserted. The above example produces: INSERT
INTO table_name (name, email, url) VALUES ('Rick', 'rick#example.com',
'example.com')
So, in your case, you can have something like this:
<form action="" method="post">
<input type="text" name="username" value="testUser123" />
<input type="password" name="password" value="yourPass666" />
<input type="text" name="email" value="email#example.com" />
<input type="submit" value="submit" />
</form>
<?php
//... extending CI
//... opening a method
$table = 'data';
//comming from somewhere, let's dynamically populated array but for testing purpose I will hardcode:
$columns('username', 'password', 'email');
foreach($columns as $column) {
$data[$column] = $_POST[$column]; // this will produce $data=array('username'=>$_POST['username'],password=....);
}
$str = $this->db->insert_string($table, $data);
?>
If you submit the form in the beginning, you will have:
INSERT INTO data (username, password, email) VALUES ('testUser123', 'yourPass666', 'email#example.com');
The whole active record class doc (insert chosen here)
http://ellislab.com/codeigniter/user-guide/database/active_record.html#insert
If you don't have to stick to the for loop, I would suggest a foreach, which should be easier (I know the little problems with for too).
foreach ($element in $array)
{
code execution here
}
Your array element is then stored in the $element (or as you like to name it) and you can execute the command found there.
Is this what you're looking for or did I get you wrong?

Categories