Edvin Tenovimas Edvin Tenovimas - 3 months ago 12
HTML Question

How to send $_POST value to MySQL, find value from different column and send back to PHP?

In

index.php
file I have this simple form:

<form method="POST" action="data.php">
<td class="head">Find ID</td>
<td><input type="text" name="entered_id"></td>
<td><input type="submit" value="Send"></td>
</form>


When a person enters a number in
entered_id
input and presses
submit
, this code should send entered value to
data.php
file from which the same value is sent to
MySQL
. In there query finds that value (it's unique) in certain table (
people
) and then finds another value in the same row but different column and return back as a result in
data.php
file.

An example:

value in table where person writes id: 42.
42 is sent to
data.php
with
$_POST
and from there to
MySQL
.
Query finds in table "people" and in certain column "number" entered
ID
. Then query fetches another value (can be any value) from the same row but from different column (
text
) and returns to
data.php
file.

data.php
file (so far):

<?php
$db = new mysqli('host', 'root', 'password', 'database');
if ($db->connect_error) {
die("Could not connect to database..: ".$db->connect_error);

$value = $_POST['entered_id'];

$query = "SELECT `number`, `text` FROM `people`"; // Missing conditionals and $value?

echo $text; // I want to return new value from column `text` here.

Answer

Firstly, here is your corrected HTML:

<form method="POST" action="data.php">
    <td class="head">Find id</td><td><input type="text" name="person" /></td>
    <td style="text-align:center;"></td><td><input type="submit" value="Send"></td>
</form>

Here is the PHP code in data.php:

<?php
// Connect to the server
$db = new mysqli('host','username','password','database');

// Your query
$query = $db->query("SELECT `number`, `text` FROM `people` WHERE `person` = '".$db->mysqli_real_escape_string($_POST['person'])."';");

if($db->num_rows == 0) { // No rows were returned
    echo 'A person with this number does not exist.';
} else { // Rows were returned
    $person = $query->fetch_object();
    echo "This person's text is ";
    echo $person->text;
}
?>

I'm also assuming that number is a primary column.

Comments