I have a update function that for now updates the required changes to MySQL database when I run index.php.
This is updating my password buy not the name field, ive been over the code and can not work out why.
Any help is greatly appreciated.
Index that tells what id and fields to update with entered data
<?php
require_once 'core/init.php';
$userInsert = DB::getInstance()->update('users', 1, array(
'password' => 'newpass',
'name' => 'Ben'
));
Function in different php that updated database
public function update($table, $id, $fields) {
$set = '';
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)) {
$set .= ',';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} = 'newpassword' WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
I believe it to be a small error or mistype but I can not see the problem.
As you can see bellow the password field has been changed but the name has not
public function update($table, $id, $fields) {
$set = '';
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = \"{$value}\"";
if($x < count($fields)) {
$set .= ',';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
Simply use of prepare and execute in PDO:
$sql = 'UPDATE '. $table .' SET username = :username, password = :password WHERE id = '. $id;
$sth = $dbh->prepare($sql);
$sth->execute(array(
':username' => 'ben',
':password' => 'newpassword'
));
private function update($table, $primaryKey, $fields) {
$query = 'UPDATE `' . $this->table . '` SET ';
foreach ($fields as $key => $value) {
$query .= '`' . $key . '` = :' . $key . ',';
}
$query = rtrim($query, ',');
$query .= ' WHERE `' . $this->primaryKey . '` = :primaryKey';
$fields['primaryKey'] = $fields['id'];
$this->query($query, $fields);
}
An example of an update function. Attention mine is inside a class and the query is another function and passes as an object.
Related
I am using below function ( i got this from internet) to fetch data from DB and its working fine. If i use where and search condition is not working properly or i have missed some thing. Can any one help me to fix this issue.
public function getRows($table,$conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$table;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
echo $sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("search",$conditions)){
$sql .= (strpos($sql, 'WHERE') !== false)?'':' WHERE ';
$i = 0;
foreach($conditions['search'] as $key => $value){
$pre = ($i > 0)?' OR ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
echo $sql .= ' LIMIT '.$conditions['limit'];
}
$query = $this->conn->prepare($sql);
$query->execute();
if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $query->rowCount();
break;
case 'single':
$data = $query->fetch(PDO::FETCH_ASSOC);
break;
default:
$data = '';
}
}else{
if($query->rowCount() > 0){
$data = $query->fetchAll();
}
}
return !empty($data)?$data:false;
}
Function used with where and Search condition
if(!empty($_POST['customer_number'])) {
$ajaxData = $auth_user->getRows(
'tablename',
array('where' => array('fieldName'=>$doc)),
array('search'=> array('fieldname1'=>$_POST['customer_number'], 'fieldname2'=>$_POST['customer_number']))
);
}
Result of the above code is
SELECT * FROM tablename WHERE cust_consum_type = '1'
Expected Result is.
select * from tablename where fieldName='somevalue' and fieldname1='somevalue' OR fieldname2='somevalue'
Help me to fix this issue.
This function is so wrong on so many levels, being critically insecure in the first place.
Instead, use vanilla PDO. Make your function this way
public function getRows($sql,$input = array()){
$stmt = $this->conn->prepare($sql);
$stmt->execute($input);
return $stmt;
}
Then just write your query right away with placeholders, pass the data in pparameters and have the result:
$sql = "select * from tablename where fieldName=:fieldName
and (fieldname1=:fieldName1 OR fieldname2=:fieldName2)";
$input = ['fieldName'=>$doc,
'fieldname1'=>$_POST['customer_number'],
'fieldname2'=>$_POST['customer_number']];
$data = $db->getRows($sql, $input)->fetchAll();
it will be safe, clean, always working, safe, flexible, safe from SQL injections and syntax errors.
When I try to update a table with the following query string using PHP:
UPDATE card_designs SET `card_price` = '6180',
`annual` = '257.3',
`initial_payment` = '6512.3'
WHERE card_id = '1'
It does not update correctly. card_price value is put in correctly. However annual comes in as 0 and initial_payment comes in as 6255.00.
It doesn't matter if the fields are a VARCHAR, DECIMAL, or DOUBLE. If the value has a decimal it's all messed up.
Also, if I run the above query in a SQL client, the query works fine.
Here is the PHP code that constructs the query. I'm using mysqli:
$sql = "UPDATE ". $table ." SET ";
$updates = array();
foreach ($variables as $field => $value) {
array_push($updates, "`$field` = '$value'");
}
$sql .= implode(', ', $updates);
//Add the $where clauses as needed
if (!empty($where)) {
foreach ($where as $field => $value) {
$value = $value;
$clause[] = "$field = '$value'";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
}
if (!empty( $limit)) {
$sql .= ' LIMIT '. $limit;
}
$query = $this->mysqli->query($sql);
I assume your database table fields datatype is Decimal(9,2)
// Prepare query
$table = "card_designs";
$variables = array(
"card_price" => "6180.00",
"annual" => "257.3",
"initial_payment" => "6512.3"
);
$where = array(
"id" => "1"
);
$sql = "UPDATE ". $table ." SET ";
$updates = array();
foreach ($variables as $field => $value)
{
array_push($updates, "$field = $value");
}
$sql .= implode(', ', $updates);
//Add the $where clauses as needed
if (!empty($where))
{
foreach ($where as $field => $value)
{
$value = $value;
$clause[] = "$field = $value";
}
$sql .= ' WHERE '. implode(' AND ', $clause);
}
if (!empty( $limit))
{
$sql .= ' LIMIT '. $limit;
}
// Run query
if ($mysqli->query($sql))
{
echo "Record updated successfully";
}
So, i have researched this everywhere and i can't see why its inserting blanks. I use pretty much the same code in another file and that one works fine. Any Help?
<?php
//Connection
$first_name = mysqli_real_escape_string($_POST [' first_name ']) ;
$last_name = mysqli_real_escape_string($_POST [' last_name ']) ;
$email = mysqli_real_escape_string($_POST [' email ']) ;
$message = mysqli_real_escape_string($_POST [' message ']) ;
$insert_sql = "INSERT INTO generaldis (first_name, last_name, email, message)
VALUES ('$first_name', '$last_name' , '$email' , '$message');";
if (!mysql_query($insert_sql,$link))
{
die('Error: ' . mysql_error());
}
echo '<h1>Whoop! Your Message Has Been Posted!</h1><br><p>Click Here To Go Back</p>';
?>
try this:
$fields = array(
'first_name' => "/[a-zA-Z-_]+/",
'last_name' => "/[a-zA-Z-_]+/",
'email' => '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/',
'message' => null
);
$permit = true;
foreach($fields AS $field => $regexp) {
if(is_null($regexp)) continue;
if(!preg_match($regexp, $_REQUEST[$field])) {
$permit = false;
break;
}
}
if($permit) {
$query = "INSERT INTO general_dis SET ";
$values = array();
foreach($fields AS $field => $regexp) {
$value = $_REQUEST[$field];
if(is_null($regexp)) {
$value = mysql_real_escape_string($value);
}
$values[] = "`".$field."`='".$value."' ";
}
$values = implode(', ', $values);
$query .= $values;
mysql_query($query);
}
I would like to add " AND " in between the key and value pair arguments for my sql query but I don't know how. I have tried search the net but unable to find a solution.
$cdatahome = fetchCategory(array("status"=>"1","home"=>"1"));
function fetchCategory(array $conditions){
$db = Core::getInstance();
$sql = "SELECT id, title FROM ruj_category WHERE ";
$params = array();
foreach ($conditions as $column => $value) {
if (preg_match('/^[a-z-.]+$/', $column)) {
$sql .= "$column = ?";
$params[] = $value;
}
}
$sql .= " order by title asc";
$res = $db->dbh->prepare($sql);
$res->execute(array_values($params));
$res = $res->fetchAll(PDO::FETCH_ASSOC);
return $res;
$where = array();
foreach ($conditions as $column => $value) {
if (preg_match('/^[a-z-.]+$/', $column)) {
$where[] = "$column = ?";
$params[] = $value;
}
}
$sql .= implode(' AND ', $where);
$cdatahome = fetchCategory(array("status"=>"1","home"=>"1"));
function fetchCategory(array $conditions){
$db = Core::getInstance();
$sql = "SELECT id, title FROM ruj_category WHERE ";
$params = array();
$i = 0;
foreach ($conditions as $column => $value) {
if (preg_match('/^[a-z-.]+$/', $column)) {
if($i != 0){
$sql .= ' AND ';
}
$sql .= "$column = ?";
$params[] = $value;
$i++;
}
}
$sql .= " order by title asc";
$res = $db->dbh->prepare($sql);
$res->execute(array_values($params));
$res = $res->fetchAll(PDO::FETCH_ASSOC);
return $res;
Usually, when I want to put something like AND or & (in the case of URLs), I create an array and implode it on the string I want in the middle. For example:
$items = array("a", "b", "c");
$output = implode(" AND ", $items);
Outputs:
"a AND b AND c"
In your case, you can do your foreach loop to build the string pieces and then use AND as glue in the implode() function as listed out by the second answer.
First, you could put the conditions into an array, as you do with the values to $params. Like $cond[]="$column = ?" and then $sql.=implode(' AND ',$cond);
To have it solved in your foreach: before the loop set $first=false; and in the loop do $sql.=($first?'':' AND ')."$column = ?"; $first=false;
I have this function
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$arr = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
$set = "";
foreach($arr as $key => $v) {
$val = is_numeric($v) ? $v : "'" . $v . "'";
$set .= $key . '=' . $val . ', ';
}
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $set, $_POST['id']);
mysql_query($sql);
if ($carry == 'yes') {
redirect($carryUrl.'?id='.$_REQUEST['id']);
} else { echo "Done!"; }
echo $sql;
}
It outputs for example: UPDATE projects SET project_name='123', project_bold='123', project_content='123', WHERE id='12'
The last comma before where is preventing it from working. Is there a way of avoiding this? Im aware of the function implode, however I am not sure how to employ it in this situation.
Yes,
$sql = substr($sql,'',-1);
I would use
$sql = rtrim($sql, ',');
Either that or instead of appending to a string, append to an array and use implode.
function updateDbRecord($db, $table, $carry, $carryUrl) {
mysql_select_db($db) or die("Could not select database. " . mysql_error());
$resultInsert = mysql_query("SHOW COLUMNS FROM " . $table . " WHERE Field NOT IN ('id')");
$fieldnames=array();
if (mysql_num_rows($resultInsert) > 0) {
while ($row = mysql_fetch_array($resultInsert)) {
$fieldnames[] = $row['Field'];
$array = array_intersect_key( $_POST, array_flip($fieldnames) ); #check if value is null otherwise do not INSERT
}
}
foreach ($array as $key => $value) {
$value = mysql_real_escape_string($value); // this is dedicated to #Jon
$value = "'$value'";
$updates[] = "$key = $value";
}
$implodeArray = implode(', ', $updates);
$sql = sprintf("UPDATE %s SET %s WHERE id='%s'", $table, $implodeArray, $_POST['id']);
mysql_query($sql);