Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

php - How to create an SQL query using an array?

I have an Array with data and I want to create an SQL statement (In which I am going to use where to where in).

I have tried to make query but no success.

SQL will be like :

SELECT * 
FROM documents 
WHERE category = "recruitment" 
AND sub_category in("forms") 
OR category = "onboarding" 
AND sub_category IN ("sop") 
OR category = "policies" 
AND sub_category IN("forms");

and Array is this :

{"Recruitment":["Forms"],"Onboarding":["Sop"],"Policies":["Forms"]}

I have tried this code :

foreach ($db_sub as $data=>$key){
    $query = "where document.category = ".$data." or where document.sub_category in ('".$key."')";
}

But getting error array to string conversion. Plz help me.

Thanks in advance.

Error : enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are trying to concatenate a string with an array. Since your array's values are also arrays, you will have to convert them to string first. It could be done with the join function.

foreach ($db_sub as $data=>$key){
    $query = "where document.category = ".$data." or where document.sub_category in ('".join(", ", $key)."')";
}

Now you shouldn't get array to string conversion error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...