2

how to pass an associative array into php functions? i tried the code below but its not working. please help me or atleast give advice. thank you so much.

addrecord.php
require 'class.php';
$fields = array(
'strname' =>$name,
'strdescript' =>$strdescript,
'straction' =>$straction
);
$addRecord = new Record();
$addRecord->addRecord($fields);


class.php
class Record{
public $db, $sql,$stmt;
public function __construct(){
$this->db = new connection();
$this->db = $this->db->dbConnect();
}
public function addRecord($fields){
$this->sql =
"INSERT INTO user
(name,description,action)
VALUES
(?,?,?)"
$this->stmt = $this->db->prepare($this->sql);
$this->stmt->bindParam(1,{$fields['strname']},PDO::PARAM_STR);
$this->stmt->bindParam(2,{$fields['strdescript']},PDO::PARAM_STR);
$this->stmt->bindParam(3,{$fields['straction']},PDO::PARAM_STR);
$this->stmt->execute();
if($this->stmt->rowCount==1){
echo "<script>alert('blah.. blah.. blah.')</script>";
}else{ 
echo "<script>alert('blah.. blah.. blah.')</script>";
}//EndIf
}//EndFunction
0

2 Answers 2

2

The line of code that is your question has proper usage.

syntax

$var = "{array['key']}";

to note:

  • the "bigger" string uses "", (because a "" string allows the use of {} for variables, and the use of '' inside ).

  • {} to tell php to replace with a variable's value

  • your array's member is the variable to use

Your error is 1) using multiple lines, for multiple lines you may do (among many other syntaxes, research them):

$var = "this " .
           "is " .
             " a string in multiple lines";

2) your sql string syntax is wrong, description is most likely a string type, strings have to be between ''

$sql = "INSERT INTO (...) VALUES ( 'my description' )"; //you lack these 's, put them
Sign up to request clarification or add additional context in comments.

1 Comment

btw, since you can do prepared statements, try to use them all the time, because they'll be safe from SQL injections (hackers) as opposed to building the sql string like on my answer.
0

For passing an empty associative array, do the following:

$result['data'] = array('content_id'=>'','user_id'=>'','title' =>'','content' =>'');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.