-2

i have try to use PDO MySQL in PHP with execute command. But i stuck with array in execute command, here code :

public static function join2ArAliasAndArValue($values=array(),$alias=array()){
    $data = array();
    for($i=0;$i<count($values);$i++){
        $data[$alias[$i]] = $values[$i];
    }

    return $data;
}

always return :

Array ( [:id_val] => 01 [:name_val] => tatang [:phone_val] => 0989989 [:address_val] => kemanggisan [:idkey_val] => 100 )

and data must be like this :

Array ( 
':id_val'       => '01' , 
':name_val'     => 'tatang', 
':phone_val'    => '0989989',
':address_val'  => 'kemanggisan',
':idkey_val'    => '100'

)

how to create like that, remove square brackets and add comma every array value, some person helpme please..

and here my function addrecord :

public static function addRecordToTable($table,$fields=array(),$values=array(),$alias=array()){
    $database = DatabaseFactory::getFactory()->getConnection();
    $table = stripslashes(strtolower($table));
    $sql = " INSERT INTO $table ";
    $fields = implode("`, `", $fields);
    $newalias = implode("', '", $alias);
    $sql .= "(`$fields`) VALUES ('$newalias')";
    $alias = explode(', ', $newalias);
    $data =  $data = Helpers::join2ArAliasAndArValue($values,$alias);

    /** DEBUG */
    Debug::debugInput('FIELDS',$fields);
    Debug::debugInput('NEW-ALIAS',$newalias);
    Debug::debugInput('SQL',$sql);
    Debug::debugInput('ALIAS',$alias);
    Debug::debugInput('DATA',$data);

    $query = $database->prepare($sql);
    $query->execute($data);
    $output = $query->rowCount() == 1 ? true : false;
}

for debug :

public static function debugInput($title,$data){
    $action = is_array($data) ? true : false;
    if($action){
        print $title . " : <b>"; print_r($data); print "</b><br />";
        return false;
    }
        print $title . " : <b>" . $data; print "</b><br />";
}

__)

ikwijaya
  • 83
  • 11
  • Have you tried to pass array to PDO execute? What happens? – u_mulder May 23 '17 at 07:36
  • 1
    Your output looks like the output from the `print_r()` function. The real array should not contain any square brackets. – Tom Udding May 23 '17 at 07:37
  • @TomUdding yes, i use print_r. If with json_encode is `{":id_val":"01",":name_val":"tatang",":phone_val":"0989989",":address_val":"kemanggisan",":idkey_val":"100"}` – ikwijaya May 23 '17 at 07:41
  • 1
    What is your exact problem? Because I don't see a problem here. Could you add your PDO code as well? – Tom Udding May 23 '17 at 07:43
  • @ikwijaya Don't use `json_encode()` or `print_r()` before passing the arguments `$values` and `$alias` to the `join2ArAliasAndArValue()` function. Pass normal `$values` and `$alias` arrays as arguments and only on the returning result from `join2ArAliasAndArValue()` apply `json_encode()` or `print_r()`. –  May 23 '17 at 07:49
  • data not really save in my db, just save $alias not $value. – ikwijaya May 23 '17 at 07:50
  • @aendeerei see the code please, iam not passing data with json_encode or print_r, its just for debug output. – ikwijaya May 23 '17 at 07:55
  • @all hahaha, i found my problem just remove ' single quotes from $newalias. – ikwijaya May 23 '17 at 07:59

4 Answers4

1

False function:

public static function addRecordToTable($table, $fields = array(), $values = array(), $alias = array()) {
    //...

    $sql = " INSERT INTO $table ";
    $fields = implode("`, `", $fields);
    $newalias = implode("', '", $alias);  // GOOD!!!: => $newalias = "alias1', 'alias2', 'alias3"
    $sql .= "(`$fields`) VALUES ('$newalias')";
    $alias = explode(', ', $newalias); // FALSE VALUES!!!: => $alias = array(alias1', 'alias2', 'alias3)
    $data = $data = Helpers::join2ArAliasAndArValue($values, $alias);

    //...
}

So, $newaliasis CORRECT (see comments in the code), because in the form with the single quotes must be inserted into the INSERT sql statement!

The $alias is used INCORRECT (see comments in the code). So, just delete

$alias = explode(', ', $newalias);

Because you don't need to implode $alias to $newalias and then explode this one to a new $alias again.

So, correct function:

public static function addRecordToTable($table, $fields = array(), $values = array(), $alias = array()) {
    //...

    $sql = " INSERT INTO $table ";
    $fields = implode("`, `", $fields);
    $newalias = implode("', '", $alias);
    $sql .= "(`$fields`) VALUES ('$newalias')";
    $data = $data = Helpers::join2ArAliasAndArValue($values, $alias);

    //...
}



EDIT 2:

I tried to refactor your code in order to give you a picture of bringing some handling strategies together. Please read the code comments for details. I would recommend

  • to use exception handling, in order to be able to always discover the errors raised by failed database operations (and not just that). You can see an older answer of me, if you wish:

Exception handling for PDO::prepare() and PDOStatement::execute() + A generalized exception handling scheme

  • to use sprintf() when building complex strings like sql statements (but don't abuse their use).

Here is the addRecordToTable() function as I see it:

public static function addRecordToTable($table, $fields = array(), $values = array(), $alias = array()) {
    // Use try-catch blocks for exception handling.
    try {
        $database = DatabaseFactory::getFactory()->getConnection();

        /*
         * Build your sql statement using sprintf() 
         * and placeholders (defined through "%s").
         * See: http://php.net/manual/en/function.sprintf.php
         */
        $sql = sprintf(
                " INSERT INTO %s (`%s`) VALUES ('%s')"
                , stripslashes(strtolower($table))
                , implode("`, `", $fields)
                , implode("', '", $alias)
        );

        // I corrected here also, because you had "$data = $data = ...".
        $data = Helpers::join2ArAliasAndArValue($values, $alias);

        $query = $database->prepare($sql);

        // Added this validation.
        if (!$query) {
            throw new Exception('The SQL statement can not be prepared!');
        }

        $executed = $query->execute($data);

        // Added this validation.
        if (!$executed) {
            throw new Exception('The PDO statement can not be executed!');
        }

        $output = $query->rowCount() == 1 ? true : false;

        /*
         * Corrected (e.g. added) here also, because you
         * have to return the results, e.g. the $output.
         */
        return $output;
    } catch (PDOException $pdoException) {
        echo '<pre>' . print_r($pdoException, true) . '</pre>';
        exit();
    } catch (Exception $exception) {
        echo '<pre>' . print_r($exception, true) . '</pre>';
        exit();
    }
}



EDIT 3:

Using PDOStatement::bindValue (or PDOStatement::bindParam) to prepare an sql statement. A general example:

//...

$sql = 'INSERT INTO demo_table (id, name) VALUES (:id, :name)';
$statement = $connection->prepare($sql);

if (!$statement) {
    throw new Exception('The SQL statement can not be prepared!');
}

// Integer binding ":id".
$statement->bindValue(':id', $id, $this->getInputParameterDataType($id));

// String binding ":name".
$statement->bindValue(':name', $name, $this->getInputParameterDataType($name));

//...

function getInputParameterDataType($value) {
    $dataType = PDO::PARAM_STR;
    if (is_int($value)) {
        $dataType = PDO::PARAM_INT;
    } elseif (is_bool($value)) {
        $dataType = PDO::PARAM_BOOL;
    }
    return $dataType;
}
  • thanks for clean my code, `$alias = explode(', ', $newalias);` – ikwijaya May 23 '17 at 08:34
  • 1
    @ikwijaya You're welcome. I'll edit my answer now, because I want to show you an eleganter way of building an sql statement. –  May 23 '17 at 08:36
  • 1
    @ikwijaya Sorry, it took a long time, but I posted now my suggestions by reediting my initial answer. Good luck with your projects. –  May 23 '17 at 09:26
  • some error `Warning: PDOStatement::execute(): SQLSTATE[42S22]: Column not found: 1054 Unknown column ''300', 'tukang sapu', '100', 'kemanggisan'' in 'field list' in D:\myfiles\xampp\htdocs\am\application\core\Query.php on line 87` => just remove single quotes **'** in ('%s') and implode("', '", $alias) because _data not really stored to db_. thanks for new code implementation. its great code. thanks a lot. – ikwijaya May 23 '17 at 10:12
  • 1
    @ikwijaya I take it it works now. Or was there a question about the "warning"-code? I thank you also. Oh, to not forget: use the `bindValue()`or the `bindParam()` functions when you prepare the sql statement, instead of passsing the bindings, e.g the input parameters array as argument to `PDOStatement::execute()`. This way you can pass the right data type of the inserting value. See my EDIT 3. –  May 23 '17 at 10:31
  • @ikwijaya Just now I was enlightened: $alias contains the input parameters. So you have totally right to do **`remove single quotes ' in ('%s') and implode("', '", $alias) because data not really stored to db.`** :-) My bad. Now I'll see your other answer. –  May 23 '17 at 10:47
0

here my success code :

public static function addRecordToTable($table,$fields=array(),$values=array(),$alias=array()){
$database = DatabaseFactory::getFactory()->getConnection();
$table = stripslashes(strtolower($table));
$sql = " INSERT INTO $table ";
$fields = implode("`, `", $fields);
$newalias = implode(", ", $alias);
$sql .= "(`$fields`) VALUES ($newalias)";
$alias = explode(', ', $newalias);
$data =  $data = Helpers::join2ArAliasAndArValue($values,$alias);

/** DEBUG */
Debug::debugInput('FIELDS',$fields);
Debug::debugInput('NEW-ALIAS',$newalias);
Debug::debugInput('SQL',$sql);
Debug::debugInput('ALIAS',$alias);
Debug::debugInput('DATA',$data);

$query = $database->prepare($sql);
$query->execute($data);
$output = $query->rowCount() == 1 ? true : false;
}
ikwijaya
  • 83
  • 11
0

@aendeerei how about this :

public static function getAllDataFromTableWithWhere($table,$fields=array(),$key=array(),$key_values=array(),$key_alias=array(),$is=true,$and=true,$orderby){
    $database = DatabaseFactory::getFactory()->getConnection();
    $table = stripslashes(strtolower($table));
    $fields = implode("`, `", $fields);
    #Debug::debugInput('FIELDS',$fields);
    if($is){
        $sql = "SELECT `$fields` FROM $table WHERE "; #`$key` = ':key_id' ORDER BY `$orderby` ASC";
        if($and){
            for($j=0;$j<count($key);$j++){
                $sql .= "`".$key[$j]. "` = ".$key_alias[$j]." AND ";
            }            
            $sql = substr($sql,0,-4);
        }else{
           for($j=0;$j<count($key);$j++){
                $sql .= "`".$key[$j]. "` = ".$key_alias[$j]." ";
            } 
            $sql = substr($sql,0,-1);
        }
    }else{
        $sql = "SELECT `$fields` FROM $table WHERE "; #`$key` LIKE `:key_id` ORDER BY `$orderby` ASC";
        if($and){
            for($j=0;$j<count($key);$j++){
                $sql .= "`".$key[$j]. "` = ".$key_alias[$j]." AND ";
            }            
            $sql = substr($sql,0,-4);
        }else{
           for($j=0;$j<count($key);$j++){
                $sql .= "`".$key[$j]. "` = ".$key_alias[$j]." ";
            } 
            $sql = substr($sql,0,-1);
        } 
    }

    $sql .= " ORDER BY $orderby";
    $data = Helpers::join2ArAliasAndArValue($key_values,$key_alias);

    #Debug::debugInput('SQL',$sql);
    #Debug::debugInput('DATA',$data);
    $query = $database->prepare($sql);
    $query->execute(array(':idkey_val' => $key_values[0]));

    return $query->fetchAll();
}

how to use try catch

ikwijaya
  • 83
  • 11
  • I just added something to exactly this answer of yours. I edited it. I don't know, if you can see it. I must go in about 5 minutes, so take a look in it and feel free to ask me, even if I'm not online. –  May 23 '17 at 11:38
0

update :

here my code for update

 public static function updateRecordToTable($table,$fields=array(),$values=array(),$alias=array(),$key=array(),$key_alias=array(),$key_values=array(),$and=true){
    try{
        $database = DatabaseFactory::getFactory()->getConnection();
        $table = stripslashes(strtolower($table));
        $data = Helpers::join4ArAliasAndArValue($values,$alias,$key_alias,$key_values);
        $update = ""; #must be declare

        for($i=0;$i<count($fields);$i++){
            $update .= "`".$fields[$i]. "` = ".$alias[$i].", ";
        } 
        $update = substr($update, 0,-2);
        Debug::debugInput('PUSH',$update);          

        if($and){
            for($j=0;$j<count($key);$j++){
                $where = "`".$key[$j]. "` = ".$key_alias[$j]." AND ";
            }            
            $where .= substr($where,0,-4);
        }else{
           for($j=0;$j<count($key);$j++){
                $where = "`".$key[$j]. "` = ".$key_alias[$j];
            }
        }
        Debug::debugInput('WHERE',$where);

        $sql = sprintf(
            "UPDATE %s SET %s WHERE %s", $table,$update,$where
        );

        $query = $database->prepare($sql);

        /** DEBUG */
        Debug::debugInput('SQL',$sql);
        Debug::debugInput('DATA',$data);

        if(!$query){
            throw new Exception('The SQL statement can not be prepared!');
        }

        $execute = $query->execute($data);
        if(!$execute){
            throw new Exception('The PDO statement can not be executed!');
        }
        return $execute;

    } catch (PDOException $pdoException) {
        echo '<pre>' . print_r($pdoException, true) . '</pre>';
        exit();
    } catch (Exception $exception) {
        echo '<pre>' . print_r($exception, true) . '</pre>';
        exit();
    }
}

UPDATE :

public static function updateRecordToTable($table,$fields=array(),$values=array(),$alias=array(),$key=array(),$key_alias=array(),$key_values=array(),$and=true){
    try{
        $database = DatabaseFactory::getFactory()->getConnection();
        $table = stripslashes(strtolower($table));
        $data = Helpers::join4ArAliasAndArValue($values,$alias,$key_alias,$key_values);
        $update = ""; #must be declare

        for($i=0;$i<count($fields);$i++){
            $update .= "`".$fields[$i]. "` = ".$alias[$i].", ";
        } 
        $update = substr($update, 0,-2);
        #Debug::debugInput('PUSH',$update);         

        if($and){
            for($j=0;$j<count($key);$j++){
                $where = "`".$key[$j]. "` = ".$key_alias[$j]." AND ";
            }            
            $where .= substr($where,0,-4);
        }else{
           for($j=0;$j<count($key);$j++){
                $where = "`".$key[$j]. "` = ".$key_alias[$j];
            }
        }
        #Debug::debugInput('WHERE',$where);
        $sql = sprintf("UPDATE %s SET %s WHERE %s", $table,$update,$where);
        $query = $database->prepare($sql);

        /** DEBUG 
        Debug::debugInput('SQL',$sql);
        Debug::debugInput('DATA',$data);
        */
        if(!$query){
            throw new Exception('The SQL statement can not be prepared!');
        }

        $execute = $query->execute($data);
        if(!$execute){
            throw new Exception('The PDO statement can not be executed!');
        }
        return $execute;

    } catch (PDOException $pdoException) {
        echo '<pre>' . print_r($pdoException, true) . '</pre>';
        exit();
    } catch (Exception $exception) {
        echo '<pre>' . print_r($exception, true) . '</pre>';
        exit();
    }
}
ikwijaya
  • 83
  • 11