William Willi
William Willi

Reputation: 186

Retrieving values from MySQL using php

Here i have made an MySQL which has the columns of "id","name","username","email",age" . Where even i made the the PHP code to retrieve the data for the given id.

eg:if the user enter id=3 then it shows the datas corresponding to the id.

But now i want set multiple inputs so that user can type more than one id and it list the corresponding datas of the particular id.

My PHP Code:

<?php 

if($_SERVER['REQUEST_METHOD']=='GET'){

    $id  = $_GET['id'];




    require_once('dbConnect.php');

    $sql = "SELECT * FROM user WHERE id='".$id."'";

    $r = mysqli_query($con,$sql);

    $result = array();

            while($res = mysqli_fetch_array($r)){

    array_push($result,array(
        "id"=>$res['id'],
        "name"=>$res['name'],
        "username"=>$res['username'],
        "email"=>$res['email'],
         "age"=>$res['age']
        )
    );
            }
    echo json_encode(array("result"=>$result));

    mysqli_close($con);

} 

Now this URL gives the perfect result: "http://www.allwaysready.16mb.com/Sort.php?id=4"

Now how can i get the corresponding values for the multiple id's?

Upvotes: 0

Views: 71

Answers (2)

James
James

Reputation: 411

Use the "IN" condition:

If id is a number:

SELECT * FROM user WHERE id IN (89, 25);

If id is a string, put the id's in quotes:

SELECT * FROM user WHERE id IN ('89N', '15B', '25E');

Rewrite your query in PHP to use the In Query condition, paying close attention to your column definition data types. Strings must be quoted for example.

Upvotes: 0

John Conde
John Conde

Reputation: 219924

You can use array syntax to pass multiple IDs to your script and use MySQL's IN() to query against them all at once.

URL: http://www.allwaysready.16mb.com/Sort.php?id[]=4&id[]1&id[]=2

$ids = $_GET['id'];
$ids = array_map(function($id) {
    return (int) $id;
}, $ids);
$ids = implode(',', $ids);

$sql = "SELECT * FROM user WHERE work IN($ids);

I cast the IDs to integers because your current code is wide open to SQL injection. You really should be using paramterized queries.

Upvotes: 1

Related Questions