-1

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?

Dan Abrey
  • 668
  • 5
  • 9
prashant
  • 13
  • 1
  • 1
  • 7
  • you can't mix MySQL APis. So this `if(isset($_REQUEST['planname'])){...}` will NEVER happen. – Funk Forty Niner Jul 27 '16 at 13:37
  • 1
    What's this `echo " – Daan Jul 27 '16 at 13:37
  • because, concatenation, `mysql_query` and basic HTML, cool. – DirtyBit Jul 27 '16 at 13:37
  • @prashant Make an ajax call on dropdown change and on ajax file fetch the price name based on the plan name and return the value in response and set the price in textbox value from the response using jquery. – Rahul Patel Jul 27 '16 at 13:39
  • ^ That, based on *"I got the list in dropdown but not able to get price according to planname dynamically.can anyone help me out of this?"* – Funk Forty Niner Jul 27 '16 at 13:43

1 Answers1

2
$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;
}
Community
  • 1
  • 1
Philipp
  • 2,754
  • 2
  • 24
  • 27
  • are you 100% sure about this? *"So your query should be: $sql = mysql_query..."* – Funk Forty Niner Jul 27 '16 at 13:45
  • based on the way he builds his select-list and concentrating on the sql only, yes. He is using the id as value, so he has to look for the id in the backend. The name of the parameter could need a change though. – Philipp Jul 27 '16 at 13:48
  • so you're suggesting that that query will work, even with a PDO connection, correct? If so, it won't. – Funk Forty Niner Jul 27 '16 at 13:49
  • assuming id is an integer field – Philipp Jul 27 '16 at 13:49
  • I'm not talking about the id/integer field, I'm talking about the mysql_ "query" function itself. – Funk Forty Niner Jul 27 '16 at 13:50
  • I take it you don't understand what I'm talking about, seeing you didn't edit your answer with the correct querying method to replace the `mysql_query()` function. Unless you don't want to. If so, then your suggestion will not work. You even said it yourself *"You are mixing the mysql_* api and PDO"* as I did also in comments up there. – Funk Forty Niner Jul 27 '16 at 13:57
  • Well, I thought we are talking about the query itself: "[...] and concentrating on the sql only, yes." So I didn't get what you meant and first had to test localy, if there is a problem with pdo and concatenating the query. – Philipp Jul 27 '16 at 14:02
  • **Duh** The OP is using PDO and then also the old and defunct and no longer available **in PHP7** `mysql_query` and you have not actually corrected his code to use PDO **Duh again** – RiggsFolly Jul 27 '16 at 14:12
  • *"but calm down please"* - I hope you're not talking about me. I tried to tell you how to fix your answer; that isn't my/our job. The OP and/or future visitors to the question may think that mixing different APIs is ok, which isn't. @Philipp Edit: You deleted your comment that I was replying to, why? – Funk Forty Niner Jul 27 '16 at 14:19
  • I was talking about the bold "Duh"s, I think I had a normal conversation with you, though I didn't get what you meant at first. Still I think it is ok, to focus on the concrete problem at first and then give the correct hints to what to change next. "@Philipp Edit: You deleted your comment that I was replying to, why?" Riggy edited his comment, so mine was nonsense. Maybe continue this in a chatroom? – Philipp Jul 27 '16 at 14:20
  • 1
    @Philipp No need to chat Philipp, everything's good here (for me anyway). – Funk Forty Niner Jul 27 '16 at 14:23
  • @Philipp-can u just help me out..how to execute this with pdo – prashant Jul 27 '16 at 16:35
  • @prashant added code and explanation of how to do it with pdo and ajax – Philipp Jul 27 '16 at 18:56
  • @Philipp- thanks alot:)worked for me – prashant Jul 28 '16 at 09:57
  • Nice :) Can you accept the answer? – Philipp Jul 28 '16 at 10:03
  • @RiggsFolly As this question is not actually about mixing the database apis (it was one of the errors but the main point was about how to archieve the dynamic changing of the other input element) could you reopen it? – Philipp Jul 28 '16 at 13:12
  • No! The reason he cannot get a result from the second query is that he is using `mysql_query()` after openning a connection using PDO which is exactly what the Dup is about – RiggsFolly Jul 29 '16 at 17:05
  • Before that, that part of the script wasn't even executed as there was no way to send the request others than typing the parameter into the url – Philipp Jul 29 '16 at 17:25
  • So I do get your point, but I think you are focussing on a somewhat 'hidden' error when the actual cause of the problem when the op posted his question was something else. – Philipp Jul 29 '16 at 17:35