Reputation: 3285
I would like to know how to convert my array to a string
$formats = $_POST['formats'];
$topics = $_POST['topics'];
for example, if I echo out the above, it just prints array. I want it to display the array as a string so that I could use it below:
$resources = "select * from resources where stage LIKE '%".$stage."%' and formats LIKE '%".$formats."%' and topics LIKE '%".$topics."%'";
I have been suggested to do something like this $formats = $_POST['formats'][0];
but i want to output the entire array as a string such "idea generation, business"
would be equivilant to ["idea generation", business"]
Upvotes: -1
Views: 85
Reputation: 1727
Since it isn't possible to determine which database you're using to make that query happen, I'll suggest you to build your query string using prepared statements and paremeterizing your values to a PDO
object based on what you may read in PHP.net documentation on the subject.
Binds a PHP variable to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement. Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
As you'll see, that way you won't have to bother converting your arrays and variables to string before accessing them, plus, you grant security to your query statements.
So, instead of implode
ing a string, you'll have something like this:
<?php
/* Execute a prepared statement by binding PHP variables */
$stage = $_POST['stage'];
$formats = $_POST['formats'];
$topics = $_POST['topics'];
$stmt = $db->prepare('select * from resources where stage LIKE % :stage % and formats LIKE % :formats % and topics LIKE % :topics %');
$stmt->bindParam(':stage', $stage);
$stmt->bindParam(':formats', $formats);
$stmt->bindParam(':topics', $topics);
$stmt->execute();
?>
EDIT: as you updated that you're using MySQLi, it'll be no different.
$stmt = $mysqli_db->prepare('select * from resources where stage LIKE % ? % and formats LIKE % ? % and topics LIKE % ? %');
// assuming all your params are strings
$stmt->bind_param('sss', $stage, $formats, $topics);
$stmt->execute();
As using mysqli, since it's an unbuffered sql query handler, you should store your results if you're looping simultaneous executions with $stmt->store_result();
Any doubts about how to use mysqli
and pdo
objects, methods and properties can be easily found in php.net documentation (linked above).
Of course, it's just a suggeston of better practices based on your apparent needs, but you can still use the implode
function to achieve your string.
Upvotes: 3
Reputation: 1332
Take a look at PHP implode
function:
http://php.net/manual/en/function.implode.php
For example, this will turn an array into a string, separating each element with a comma:
$string = implode(',', $array);
Upvotes: 2