mvasco
mvasco

Reputation: 5107

Using String as array and use it in a query

I am working on a PHP file and getting via POST this string:

$temas = $_POST['temas']; //$temas = ".45.12.34"

Where each of the numbers should be the id for a table record.

And I have following query

$query = "SELECT * FROM tb_preguntas WHERE tema = '".$temas."'";

I need to put in the WHERE part of the query each of the received id

Something like that: ... WHERE tema = 45 OR tema = 12 OR tema = 34

Of course, on each execution the string changes.

I have tried using the PHP explode function, but I don't know how to implement the result in the query.

Upvotes: 0

Views: 141

Answers (5)

Mark Salvania
Mark Salvania

Reputation: 484

Use explode() to split those numbers by .And it must turn into array.

Then run your queries into a loop using the lenth of the array like this:

$id = explode('.',$temas);
    foreach($id as $temas_id) {    
      $query = "SELECT * FROM tb_preguntas WHERE tema = '".$temas_id."'";
      if(isset($conn->query(query ))) {
        // Execute code here if there's a result.
      }
    }

Upvotes: 1

treyBake
treyBake

Reputation: 6560

My answer won't differ too much from everyone else's but it is an answer to address SQL injection + a solution

$temas = implode(',', explode('.', $_POST['temas']));
$temas = trim($temas);

$res = $conn->prepare('select * from `tb_preguntas` WHERE `tema` in (:temas)');
$res->execute(array(':temas' => $temas));

here we use a prepared statement, now you're code is safe woop woop

Upvotes: 4

Hiren Spaculus
Hiren Spaculus

Reputation: 795

Please try this code.

$temas = $_POST['temas']; 

$temas = explode('.',$temas);

$query = mysql_query("SELECT * FROM test_stipe WHERE tema in '".implode("', '", $temas)."'");

This code is working fine.

Upvotes: 0

Aurangzeb
Aurangzeb

Reputation: 1626

best case scenario

$temas = implode(',', explode( '.', $_POST['temas']));
$query = "select * from tb_preguntas WHERE tema in (" . $temas . ")";

but your case, . comes first that makes life so much harder, so a better solution would be

$temas1 = explode( '.', $_POST['temas'] );
$temas2 = array();
foreach( $temas1 as $value ) {
   if( is_numeric( $value )) $temas2[] = $value;
}
$query = "select * from tb_preguntas WHERE tema in (" . implode( ',' , $temas2 ) . ")";

Upvotes: 1

Dawson Irvine
Dawson Irvine

Reputation: 334

As suggested above you can use the IN() function of mysql, however you have to remove the first period '.' and change the rest to commas ','.

$query = "SELECT * FROM `tb_preguntas` WHERE `tema` IN('".str_replace('.',',',trim($temas,'.'))."') ";

Upvotes: 1

Related Questions