M
M
myrade2015-02-12 09:10:39
PHP
myrade, 2015-02-12 09:10:39

How to correctly compose a mysql php query to get the necessary data?

When executing the code below, I get:
{"device":[{"marka":"6","sn":"qw1454","kab":"16","invn":"7551","type": "2","fio":"2"}],"success":1}
For example, there is a types table with idtype and name columns. It is necessary to display in the type field in the result instead of "2" what is in types.name under idtype=2, etc.
How to make a correct request or change something in the code to end up with:
{"device":[{"marka":"Samsung","sn":"qw1454","kab":"582","invn ":"7551","type":"Monitor","fio":"Ivanov"}],"success":1}

<?php
 $response = array();
 require 'db_connect.php';
 $db = new DB_CONNECT();
 if (isset($_GET["invn"])) {
    $invn = $_GET['invn'];
     $result = mysql_query("SELECT * FROM device WHERE invn = $invn");
     if (!empty($result)) {
        if (mysql_num_rows($result) > 0) {
             $result = mysql_fetch_array($result);
             $device = array();
            $device["invn"] = $result["invn"];
            $device["type"] = $result["type"];
            $device["marka"] = $result["marka"];
            $device["sn"] = $result["sn"];
            $device["fio"] = $result["fio"];
            $device["kab"] = $result["kab"];
            $response["success"] = 1;
             $response["device"] = array();
             array_push($response["device"], $device);
             echo json_encode($response);
        } else {
            $response["success"] = 0;
            $response["message"] = "No product found";
             echo json_encode($response);
        }
    } else {
        $response["success"] = 0;
        $response["message"] = "No product found";
         echo json_encode($response);
    }
} else {
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
     echo json_encode($response);
}
?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Entelis, 2015-02-12
@myrade

google "mysql join"

SELECT device .*,type.name as type_name
FROM device 
JOIN type ON type.idtype = device.type
WHERE device.invn = $invn

A
Alexander N++, 2015-02-12
@sanchezzzhak

Don't do it

$invn = $_GET['invn'];
"SELECT * FROM device WHERE invn = $invn"

If you do not want to lose data or the server.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question