-2

hey guys I have an SQL in PHP with PDO method and I want use my function inside this SQL.

My function:

function columns(){
    return "id,name";
}

My SQL code:

try{
    $connection->beginTransaction();
    $connection->exec("INSERT INTO table (".columns().") VALUES (1,'John')");
    $connection->commit();
}catch(...){
...
}

But its not working what can i do help me please.

The SQL is becoming like this :

INSERT INTO table() VALUES (1,'John')

The problem is the columns() function is not returning on the SQL but if we print the columns() function its will print. (tested with print_r(columns());)

6
  • 2
    Be more specific. What isn't working? What is the error? Commented Jun 26, 2020 at 22:40
  • @Jacobm001 the function is not working on SQL. question is edited also. Commented Jun 26, 2020 at 22:45
  • 1
    I don't see why the function's return value is dropped. Does it work in a variable? Is it possible that your function is overwritten in your scope (class and such)? Commented Jun 26, 2020 at 22:56
  • @ΔO'deltazero' yes its possible but I don't think its gonna work on class also Commented Jun 26, 2020 at 23:02
  • I cannot reproduce the behaviour in the question. Commented Jun 26, 2020 at 23:16

1 Answer 1

1

Use a variable to store the answer of that function and add it to your string

try{
    $mycolumnname = columns();
    $connection->beginTransaction();
    $sql="INSERT INTO table (".$mycolumnname.") VALUES (1,'John')";
    $connection->exec($sql);
    $connection->commit();
}catch(...){
...
}
Sign up to request clarification or add additional context in comments.

8 Comments

Good for debugging, but I don't think it should make any difference.
Glad to hear that, can you elaborate? What is the difference joining the query string using intermediate variable instead of the functions return value?
@nbk I tried this before you but it's not gonna work i even used this way : INSERT INTO table ($mycolumnname) both are same and not gonna work. still same error like before.
look there are countle4ss threads here like yours see stackoverflow.com/questions/12296624/…
@nbk no its difference. its 100% something else
|

Your Answer

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