Want to fetch data from database based on dropdown list selection using php [duplicate]

天涯浪子 提交于 2019-12-13 08:06:43

问题


I have a php file and mysql database with fields named planname and price,and i want a dropdown list of all the planname from database and according to the planname the price of particular planname should be shown in text box below. Here is my php file;

<?php

$servername = xxxxxxx;
$username = xxxxxx;
$password = xxxxxx";


try {
    $conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }




$sql="SELECT id,planname,price FROM plan"; 

/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */

echo "<select name=planname value=''>Plan Name</option>"; // list box select command

foreach ($conn->query($sql) as $row){//Array or records stored in $row

echo "<option value=$row[id]>$row[planname]</option>";


/* Option values are added by looping through the array */ 

}

 echo "</select>";// Closing of list box

if(isset($_REQUEST['planname'])){
  // connection should be on this page  
    $sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);
    $res = mysql_fetch_assoc($sql);
    echo $res['price'];die;
}

echo '<input type="text3" name="price[]" id="price" value="', $row['price'], '" disabled="disabled" />';

?>

I got the list in dropdown but not able to get price according to planname dynamically.can anyone help me out of this?


回答1:


$sql = mysql_query("select price from plan where planname =".$_REQUEST['planname']);

You are searching in the column planname, but by defining the <option>'s as

echo "<option value=$row[id]>$row[planname]</option>";

You are sending the id as value.

So your query should be:

$sql = mysql_query("select price from plan where id =".$_REQUEST['planname']);
// better: pdos prepared statements
$stmt = $conn->prepare("select sub_id from sub where sub_id = ?");
$stmt->execute(array($_GET['planname']));

Also read the other comments. You are mixing the mysql_* api and PDO, you should only use PDO. Why shouldn't I use mysql_* functions in PHP? And see this when you are at it: How can I prevent SQL injection in PHP?

The structure of your code will make maintainance really troublesome, you should first do all the logical work, gather all the data and then display your html and the data in the next step.

How to do implement your plan

You need / might want to use two different scripts, to get your dynamic ui. (You could use the same file but things could get messy and it is better to split tasks)

1. The frontend:

As previously said, you should structure code in a meaningful order. You can see I am first setting up the database connection, then doing the querying and already fetching of the result. This way I already have all the data needed before I start to output other stuff (if something goes wrong as in I notice there is something invalid with the data/whatever I could still redirect to another page as there has not been a header sent).

To start the output, I added some basic HTML structure to your script, don't know if you already had it, at least it is not in your snippet.

So I added header and body, in the header is the javascript code which will execute the request to the backend and receive the response to act accordingly.

Note:

I am not really familiar with vanilla javascript, so I just followed a tutorial http://www.w3schools.com/ajax/ajax_php.asp

I think you should check out jQuery if you haven't yet, it makes things really really easy.

Other than that I reduced some noise and used other code formatting than you, basically I don't like to use echo to output my HTML as some IDEs are not able to do syntax highlighting when done so.

I also added a <p></p> in which the error message can be displayed to the user, if something in the backend goes wrong.

<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';

try {
    $conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    trigger_error("Connection failed: " . $e->getMessage());
}
$selectPlans = "SELECT id, planname, price FROM plan";
$rows = $conn->query($selectPlans)->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function getPrice(id){
                var xmlhttp = new XMLHttpRequest();
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                        var jsonObj = JSON.parse(xmlhttp.responseText);
                        if(jsonObj.success === true){
                            document.getElementById("price").value = jsonObj.price;
                        }else{
                            document.getElementById("price").innerHTML = jsonObj.message;
                        }
                    }
                };
                xmlhttp.open("GET", "ajax.php?id=" + id, true);
                xmlhttp.send();
            }
        </script>
    </head>
<body>
    <select name="planname" id="plannameSelect" onchange="getPrice(this.value)">
    <?php foreach ($rows as $row): ?>
        <option value="<?= $row['id'] ?>"><?= $row['planname'] ?></option>
    <?php endforeach; ?>
    </select>
    <input type="text" name="price[]" value="" id="price" disabled="disabled">
    <p id="error"></p>
</body>

2. The backend: (in this case called ajax.php)

A simple piece of code, nothing special to do.

First step: validating the input. In this case, I simply check if there is an id in the $_GET-Array. I used json_encode() on an array in which I tell the frontend whether the operation was successfull or not. The first case of failure would be if there was no id.

Then connect to the database, ask for errors and if so return them immediately to the user (by using echo), again via the json_encoded array.

Prepare the statement for selecting the price of the id (I skipped the error check here, you might want to add it). Then execute it.

Check if it was successfull -> return the json_encoded array as success and with the price, or set success false again and return the array with an error message.

<?php
$servername = 'xxxxxxx';
$username = 'xxxxxx';
$password = 'xxxxxx';

if(!isset($_GET['id'])){
    echo json_encode(array('success' => false, 'price' => '', 'message' => 'no id given'));
    exit;
}

try {
    $conn = new PDO("mysql:host=$servername;dbname=vnet", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    trigger_error("Connection failed: " . $e->getMessage());
    echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened' . $e->getMessage()));
    exit;
}

$stmt = $conn->prepare("SELECT price FROM plan WHERE id = ?");
$stmt->execute(array($_GET['id']));
$result = $stmt->fetch(PDO::FETCH_ASSOC);

if($result === false){
    trigger_error('Query failed: ' . $conn->errorInfo());
    echo json_encode(array('success' => false, 'price' => '', 'message' => 'shit happened'));
    exit;
} else {
    echo json_encode(array('success' => true, 'price' => $result['price'], 'message' => ''));
    exit;
}


来源:https://stackoverflow.com/questions/38614551/want-to-fetch-data-from-database-based-on-dropdown-list-selection-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!