UPDATE record serialized - php mysql - php

I have this problem, I have to update a record of a table that has the values of a serialized column. the call to the function works and passes the data correctly. I can enter the record, but I can not update. This is my code:
public function update($user_id, $array_check)
{
$arrayB = array();
$array_check = unserialize($array_check);
foreach ($array_check $key => $value) {
if($value["id"] == $array_check){
$idRow = $value["id"];
if($value["value"] == "0"){
$valueRow = "1";
}else{
$valueRow = "0";
}
}else{
$idRow = $value["id"];
$valueRow = $value["value"];
}
$row = array("id" => $idRow, "value" => $valueRow);
$arrayB[] = $row;
}
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id');
$row = $stmt->execute(array(':user_id' => $user_id, ':docs_selected' => serialize($arrayB) ) );
return $arrayB;
}

edit.
Replace this:
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id);
with:
$deseralized = serialize($arrayB);
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = '$deseralized ' WHERE user_id = '$user_id');

Related

PHP PDO dynamic update query to MYSQL

I have a form with an image upload and text inputs. it keeps replacing the profile_picture field with NULL. Therefore, I'm trying to create a dynamic update query, where if one value is empty it's excluded from the query altogether.
Any help is appreciated.
IMAGE UPLOAD:
if (!empty($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] == UPLOAD_ERR_OK) {
// Rename the uploaded file
$uploadName = $_FILES['profile_picture']['name'];
$tmp_name = $_FILES['profile_picture']['tmp_file'];
$ext = strtolower(substr($uploadName, strripos($uploadName, '.')+1));
$filename = round(microtime(true)).mt_rand().'.'.$ext;
if (move_uploaded_file($_FILES['profile_picture']['tmp_name'],'../profile_picutres/'. $filename)) {
}
}
UPDATE QUERY:
$stmt = $dbh->prepare("UPDATE 001_user_table_as SET profile_picture=:profile_picture, first_name=:first_name, last_name=:last_name, phone_number=:phone_number, nationality=:nationality, years_experience=:years_experience, data=:data WHERE id=:id");
$stmt->bindParam(':profile_picture', $filename);
$stmt->bindParam(':first_name', $first_name);
$stmt->bindParam(':last_name', $last_name);
$stmt->bindParam(':phone_number', $phone_number);
$stmt->bindParam(':nationality', $nationality);
$stmt->bindParam(':years_experience', $years_experience);
$stmt->bindParam(':data', $cv_data);
$stmt->bindParam(':id', $user_id);
if($stmt->execute()){
$response["message"] = 'success';
}else{
$response["message"] = 'error';
$errors++;
}
Below is the solution, where an input is empty, it'll use the existing data in that field and will accept not only $_POST variables, but all variables.
// the list of allowed field names
$allowed = ["profile_picture","first_name","last_name", "phone_number", "nationality", "years_experience", "data" ];
// initialize an array with values:
$params = [];
// initialize a string with `fieldname` = :placeholder pairs
$setStr = "";
// loop over source data array
foreach ($allowed as $key)
{
if (!empty([$key]) || $key != "" || $key != NULL)
{
if($GLOBALS[$key] != NULL){
$setStr .= "`$key` = :$key ,";
$params[$key] = $GLOBALS[$key];
}else{
$setStr .= "`$key` = $key ,";
}
}else{
}
}
$setStr = rtrim($setStr, ",");
$params['id'] = $_SESSION['user_id'];
$dbh->prepare("UPDATE 001_user_table_as SET $setStr WHERE id = :id")->execute($params);
Rather than relying on a global variable, you could use a function to generate the SQL string that depends only on a table name, allowed columns and columns provided. This allows you to react to any source of request (forms, raw body, ...).
<?php
function getPreparedUpdateSql(string $table, array $allowedColumns, array $columns): string
{
$set = [];
foreach ($columns as $column) {
if (!in_array($column, $allowedColumns)) {
continue;
}
$set[] = "$column = :$column";
}
$set = implode(", ", $set);
return "UPDATE $table SET $set WHERE id = :id";
}
And here is an example usage of that function anywhere you need it.
<?php
$connection = new PDO("mysql:dbname=dbname;host=127.0.0.1", "user", "pass");
$jsonRequestBody = json_decode(file_get_contents("php://input"), true);
// ["firstname" => "firstname", "lastname" => "lastname"]
$entityId = 1;
$table = "users";
$allowedColumns = ["firstname", "lastname", "email", "role"];
$columns = array_keys($jsonRequestBody);
// ["firstname", "lastname"]
$sql = getPreparedUpdateSql($table, $allowedColumns, $columns);
// UPDATE users SET firstname = :firstname, lastname = :lastname WHERE id = :id
$query = $connection->prepare($sql);
$query->execute([...$jsonRequestBody, "id" => $entityId]);
If you want to use it on traditional forms, you can simply change the columns variable to this.
<?php
$columns = array_keys($_POST);
Do not forget to check for thrown exceptions!

Import a single CSV file into multiple tables in MySQL

I would like to import a single CSV with 7 columns into 2 tables in MySQL.
Columns 1, 2 and 3 go into a single row in table1. Columns 4 and 5 go as a row in table2. Columns 6 and 7 go as a row again in same table2.
How can this be done using PHP or mysql directly?
First fetch all values from csv and store it in an array. Then maintain your array as per your requirement and then start looping and inserting.
<?php
$efected = 0;
$file_temp = $_FILES["file"]["tmp_name"];
$handle = fopen($file_temp, "r"); // opening CSV file for reading
if ($handle) { // if file successfully opened
$i=0;
while (($CSVrecord = fgets($handle, 4096)) !== false) { // iterating through each line of our CSV
if($i>0)
{
list($name, $gender, $website, $category, $email, $subcat) = explode(',', $CSVrecord); // exploding CSV record (line) to the variables (fields)
//print_r($subcat); sub_cat_ids
if($email!='')
{
$chk_sql = "select * from employees where employee_email='".$email."'";
$chk_qry = mysqli_query($conn, $chk_sql);
$chk_num_row = mysqli_num_rows($chk_qry);
$cat_array = array(trim($category));
$subcat_array = explode( ';', $subcat );
if(count($subcat_array)>0)
{
$subcat_array_new = array();
foreach($subcat_array as $key => $val)
{
$subcat_array_new[] = trim($val);
}
}
$cat_sub_cat_merge = array_merge($cat_array, $subcat_array_new);
$cat_subcat_comma = implode( "','", $cat_sub_cat_merge );
foreach($cat_array as $cat_key => $cat_val)
{
$chk_cat_sql = "select * from employee_cats where cats_name = '".$cat_val."'";
$chk_cat_qry = mysqli_query($conn, $chk_cat_sql);
$chk_cat_num_row = mysqli_num_rows($chk_cat_qry);
//$all_cat_array = array();
if($chk_cat_num_row == 0)
{
$new_cat_ins = "insert into employee_cats set cats_name = '".$cat_val."', parent_cat_id = '0' ";
$new_cat_ins_qry = mysqli_query($conn, $new_cat_ins);
}
}
foreach($subcat_array_new as $subcat_key => $subcat_val)
{
$chk_subcat_sql = "select * from employee_cats where cats_name = '".$subcat_val."'";
$chk_subcat_qry = mysqli_query($conn, $chk_subcat_sql);
$chk_subcat_num_row = mysqli_num_rows($chk_subcat_qry);
//$all_cat_array = array();
if($chk_subcat_num_row == 0 && trim($subcat_val)!='')
{
//$category
$get_catid_sql = "select * from employee_cats where cats_name = '".trim($category)."'";
$chk_catid_qry = mysqli_query($conn, $get_catid_sql);
$fetch_cat_info = mysqli_fetch_array($chk_catid_qry);
$fetch_cat_id = $fetch_cat_info['cats_id'];
$new_subcat_ins = "insert into employee_cats set cats_name = '".$subcat_val."', parent_cat_id = '".$fetch_cat_id."' ";
$new_subcat_ins_qry = mysqli_query($conn, $new_subcat_ins);
}
}
$get_cat_sql = "select * from employee_cats where cats_name in ('".$cat_subcat_comma."')";
$get_cat_qry = mysqli_query($conn, $get_cat_sql);
$get_cat_num_row = mysqli_num_rows($get_cat_qry);
$sub_category_ids = array();
if($get_cat_num_row>0)
{
while($fetch_cat_id = mysqli_fetch_array($get_cat_qry))
{
if($fetch_cat_id['parent_cat_id']==0)
{
$category_id = $fetch_cat_id['cats_id'];
}
else
{
$sub_category_ids[] = $fetch_cat_id['cats_id'];
}
}
$sub_cat_id_vals_comma = implode(",", $sub_category_ids);
}
else
{
$category_id = 0;
$sub_cat_id_vals_comma = "";
}
if($chk_num_row>0)
{
// and here you can easily compose SQL queries and map you data to the tables you need using simple variables
$update_sql = "update employees set
employee_name='".$name."',
employee_gender='".$gender."',
employees_website='".$website."',
employees_cat_id='".$category_id."',
sub_cat_ids='".$sub_cat_id_vals_comma."'
where employee_email='".$email."'";
$mysqli_qry = mysqli_query($conn, $update_sql);
}
else
{
// and here you can easily compose SQL queries and map you data to the tables you need using simple variables
$insert_sql = "insert into employees set
employee_name='".$name."',
employee_gender='".$gender."',
employees_website='".$website."',
employees_cat_id='".$category_id."',
sub_cat_ids='".$sub_cat_id_vals_comma."',
employee_email='".$email."'";
$mysqli_qry = mysqli_query($conn, $insert_sql);
}
$efected = 1;
}
}
$i++;
}
fclose($handle); // closing file handler
}
if($efected==1)
{
header('location:'.$site_url.'?import=success');
}
else
{
header('location:'.$site_url.'?import=failed');
}
?>

How does one pass the properties of a $_POST to a Function?

I would like to pass the properties to a function to Update details in a database. I want all the columns that were selected in the form to be passed to a function. Frankly, I don't know what to do.
My code is the following:
if (isset($_POST["updateWineButton"])) {
$wineID = $_POST["wineID"];
$wineCountryID = $_POST["wineCountryID"];
$wineSizeID = $_POST["wineSizeID"];
$wineRatingID = $_POST["wineRatingID"];
$wineColourID = $_POST["wineColourID"];
$packageID = $_POST["packageID"];
$wineCategoryID = $_POST["wineCategoryID"];
$wineCode = $_POST["wineCode"];
$price = $_POST["price"];
$description = $_POST["description"];
$wineRating = $_POST["wineRating"];
$wineIMG = $_POST["wineIMG"];
updateWine($updateWine);
$status = "$description has been updated.";
}
Update Wine Function
function updateWine($wineUpdate)
{
global $pdo;
$statement = $pdo->prepare("UPDATE WINE SET wineID=?, wineCountryID=?, wineSizeID=?, wineRatingID, wineColourID=?,
packageID=?, wineCategoryID=?, wineCode=?, price=?, description=?, wineRating=?, wineIMG=?
WHERE wineID=?");
$statement->execute([$wineUpdate->wineID,
$wineUpdate->wineCountryID,
$wineUpdate->wineSizeID,
$wineUpdate->wineRatingID,
$wineUpdate->wineColourID,
$wineUpdate->packageID,
$wineUpdate->wineCategoryID,
$wineUpdate->wineCode,
$wineUpdate->price,
$wineUpdate->description,
$wineUpdate->wineRatingID,
$wineUpdate->wineIMG]);
$statement->fetch();
}
Something like the following should work for you:
function updateWine()
{
global $pdo;
$keys = [
"wineID", "wineCountryID", "wineSizeID", "wineRatingID", "wineColourID", "packageID", "wineCategoryID",
"wineCode", "price", "description", "wineRating", "wineIMG",
];
$results = [];
foreach ($keys as $index) {
if (isset($_POST[$index])) {
$results[$index] = $_POST[$index];
}
}
$statement = $pdo->prepare("UPDATE WINE SET " . implode('=?, ', array_keys($results)) . "=? WHERE wineID =?");
$statement->execute(array_merge(array_values($results), [$_POST['wineID']]));
$statement->fetch();
}
if (isset($_POST["updateWineButton"]) && isset($_POST['wineID'])) {
updateWine();
}
Hope this helps!
if I understand correctly you want to do something like this,
if (isset($_POST["updateWineButton"])) {
$result = updateWine($_POST);
if($result){
$status = "$description has been updated.";
}else{
$status = "An error occurred.";
}
}
//your function woud then look like ...
function updateWine($postdata){
$wineID = $postdata["wineID"];
$wineCountryID = $postdata["wineCountryID"];
$wineSizeID = $postdata["wineSizeID"];
$wineRatingID = $postdata["wineRatingID"];
$wineColourID = $postdata["wineColourID"];
$packageID = $postdata["packageID"];
$wineCategoryID = $postdata["wineCategoryID"];
$wineCode = $postdata["wineCode"];
$price = $postdata["price"];
$description = $postdata["description"];
$wineRating = $postdata["wineRating"];
$wineIMG = $postdata["wineIMG"];
//udpate your database with the above values
//check if update is successful
return true;
//else if there was an error
return false;
}

Joomfish migration script returns error

Here is a script that upgrades joomfish (joomla translation component) from joomla 1.5 to 2.5:
$db = new PDO("mysql:host=localhost;dbname=db;charset=UTF8", "root", "pass");
$stmt = $db->prepare("select distinct(jfc.reference_id),c.catid,jfc.language_id,c.modified,c.modified_by,c.version,c.modified_by ,c.ordering,c.created_by,c.metadesc ,c.created_by_alias from jos_jf_content jfc ,jos_content c where jfc.reference_id = c.id and jfc.reference_table = 'content' ");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
$count_row = $db->prepare("select * from jos_jf_content where reference_id = ? and language_id = ?");
$count_row->bindValue(1, $row['reference_id']);
$count_row->bindValue(2, $row['language_id']);
$lang_code = $db->prepare("select lang_code from j25_languages where lang_id = ?");
$lang_code->bindValue(1, $row['language_id']);
$lang_code->execute();
$l_code = $lang_code->fetch(PDO::FETCH_OBJ);
$language_code = $l_code->lang_code;
$count_row->execute();
$title ="";
$fulltext ="";
$introtext ="";
$alias ="";
$published ="";
while($col = $count_row->fetch(PDO :: FETCH_ASSOC))
{
if($col['reference_field'] == "title")
{
$title = $col['value'];
}
if($col['reference_field'] == "fulltext")
{
$fulltext = $col['value'];
}
if($col['reference_field'] == "introtext")
{
$introtext = $col['value'];
}
if($col['reference_field'] == "alias")
{
$alias = $col['value'];
}
$published = $col['published'];
}
$exe = $db->prepare("insert into j25_content (`title`,`alias`,`introtext`,`fulltext`,`published`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`version`,`ordering`,`metadesc`,`language`) values(:title,:alias,:introtext,:fulltext,:published,:categoryid,:created,:created_by,:created_by_alias,:modified,:modified_by,:version,:ordering,:metadesc,:language_code)");
$exe->execute(array(':title' => $title,':alias' => $alias,':introtext' => addslashes($introtext),':fulltext' => addslashes($fulltext),':published' => ".$published.",':categoryid' => $row['catid'],':created' => date("Y-m-d H:i:s"),':created_by' => $row['created_by'],':created_by_alias' => "".$row['created_by_alias']."",':modified' => date("Y-m-d H:i:s"),':modified_by' =>$row['modified_by'],':version' => $row['version'],':ordering' => $row['ordering'],':metadesc' => $row['metadesc'],':language_code' => $language_code));
$i = $db->lastInsertId('id');
$asst = $db->prepare("select asset_id from j25_categories where id = ? ");
$asst->bindValue(1, $row['catid']);
$asst->execute();
$asst_id = $asst->fetch(PDO::FETCH_OBJ);
$cassetid = $asst_id->asset_id;
$sel = $db->prepare("select lft,rgt FROM `j25_assets` where id = (SELECT max(id) FROM `j25_assets`)");
$sel->execute();
$select = $sel->fetch(PDO::FETCH_OBJ);
$left = $select->lft;
$right = $select->rgt;
$left=$left+1;
$right = $right+1;
$stmt = $db->prepare("insert into j25_assets (`parent_id`,`lft`,`rgt`,`level`,`name`,`title`) values(:cassetid,:left,:right,:level,:name,:title)");
$stmt->execute(array(':cassetid' => $cassetid,':left' => $left,':right' => $right,':level' => 4,':name' => "com_content.article.".$i,':title' => $title));
$insertedId = $db->lastInsertId('id');
$update = $db->prepare("update j25_content set asset_id = ? where id = ?");
$update->bindValue(1, $insertedId);
$update->bindValue(2, $i);
$update->execute();
$stmt = $db->prepare("insert into j25_jf_translationmap (language,reference_id,translation_id,reference_table) values (:language_code,:reference_id,:translation_id,:content)");
$stmt->execute(array(':language_code' => $language_code,':reference_id' => $row['reference_id'],':translation_id' => $i,':content' => 'content'));
}
Line of code:
$language_code = $l_code->lang_code;
Returns:
Trying to get property of non-object
I'm not an author of the script and not good in PHP, but I've tried to print_r($l_code->lang_code); and I got expected result en-GB from [lang_code] => en-GB. What I need to change in this code? Thanks.
The line $language_code = $l_code->lang_code > 0; sets $language_code to boolean value. Try var_dump($l_code); and var_dump($language_code); to debug your results. You should also check if $l_code actually is an object, or perhaps null was returned. Hope that helps.

Dynamically create a SQL statment from passed values in PHP

I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.

Categories