get all mysql row data after selecting name from dropdown - php

Below is the php code I'm using to populate a select dropdown with the variable "full_name".
$sql = "SELECT * FROM Entries";
$result = mysql_query($sql);
echo "<select name='full_name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['full_name'] ."'>" . $row['full_name'] ." </option>";
}
echo "</select>";
I would like to be able to select a name from the dropdown list and display all the relevant data for that specific row so it can be easily seen by the admins.
Basically
select name (details populate below)
Name: $full_name<br>
DOB: $dob<br>
Work Phone: $work_phone<br>
etc...
Maybe something like this?
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "Name :{$row['full_name']} <br> ".
"DOB : {$row['dob']} <br> ".
"Work Phone : {$row['work_phone']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
I just don't know how to tie the dropdown selection to correctly display the information for that person's name. Any help is appreciated!
Thanks
UPDATE:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).on("change", "#full_name", function(){
var elem = $(this),
full_name = elem.val();
$(".info").hide(200); /* HIDE ALL OTHER INFORMATION */
$(".info-"+full_name).show(200); /* SHOW THE INFO OF THE SELECTED FULL NAME */
});
</script>
</head>
<body>
<select name="full_name" id="full_name">
<?php
$connection = new mysqli("XXXX", "XXXX", "XXXX", "XXXX");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$info = ''; /* WE'LL BE STORING THEIR INFORMATION HERE */
$stmt = $connection->prepare("SELECT full_name, dob, work_phone FROM Entries");
if ( false===$stmt ) { die('prepare() failed: ' . htmlspecialchars($mysqli->error)); }
$stmt->execute();
$stmt->bind_result($full_name, $dob, $workphone);
while($stmt->fetch()){
echo '<option value="'.$full_name.'">'.$fullname.'</option>';
$info .= '<div class="info info-'.$fullname.'" style="display:none">'.$dob.' - '.$work_phone.'</div>';
}
$stmt->close();
echo '</select>';
echo $info; /* DISPLAY THE INFOs, BUT NOT REALLY BECAUSE THEY ARE HIDDEN */
?>
</body>
</html>
UPDATE:
id
requested_action
full_name
birth_date
sex
work_location
work_phone
hire_date
coverage_choice
network_choice
plan_choice
dependant_name_1
dependant_relationship_1
dependant_dob_1
dependant_sex_1
dependant_name_2
dependant_relationship_2
dependant_dob_2
dependant_sex_2
dependant_name_3
dependant_relationship_3
dependant_dob_3
dependant_sex_3
dependant_name_4
dependant_relationship_4
dependant_dob_4
dependant_sex_4
spouse_coverage
employee_enroll
signature
date_today
reg_date
UPDATE: found error with connection - now I get blank output
<body>
<select name="full_name" id="full_name">
<option value="Customer, Joe"></option><option value="Customer, Susie"></option><option value="Customer, Joe"></option><option value="Customer, Josie, B"></option><option value="Renoir, Thomas"></option><option value="Customer, Joe"></option></select><div class="info info-" style="display:none"> - </div><div class="info info-" style="display:none"> - </div><div class="info info-" style="display:none"> - </div><div class="info info-" style="display:none"> - </div><div class="info info-" style="display:none"> - </div><div class="info info-" style="display:none"> - </div></body>
</html>

You can achieve this using Javascript. But we will be using a Javascript library called jQuery.
Oh, and don't use deprecated mysql_* extension. We will be using mysqli_* extension instead.
Let's prepare first your HTML by adding an id tag on your <select></select> field.
echo '<select name="full_name" id="full_name">';
Then on your while loop, let's get the other information from each row.
$info = ''; /* WE'LL BE STORING THEIR INFORMATION HERE */
$stmt = $connection->prepare("SELECT id, full_name, birth_date, work_phone FROM Entries"); /* SEE HOW TO ESTABLISH CONNECTION TO YOUR DATABASE USING mysqli AT THE BOTTOM */
$stmt->execute();
$stmt->bind_result($id, $fullname, $dob, $workphone); /* CORRESPONDS TO THE SELECTED COLUMNS FROM YOUR QUERY */
while($stmt->fetch()){
echo '<option value="'.$id.'">'.$fullname.'</option>';
$info .= '<div class="info info-'.$id.'" style="display:none">
Date of Birth: '.$dob.'<br>
Tel. Phone (work): '.$workphone.'
</div>';
}
$stmt->close();
echo '</select>';
echo $info; /* DISPLAY THE INFOs, BUT NOT REALLY BECAUSE THEY ARE HIDDEN */
Then, let's create the script to display the information of selected full_name:
<script src="jquery-1.9.1.min.js"></script> <!-- REPLACE JS FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED AND THE DIRECTORY WHERE YOU PUT IT -->
<script>
$(document).on("change", "#full_name", function(){
var elem = $(this),
id = elem.val();
$(".info").hide(200); /* HIDE ALL OTHER INFORMATION */
$(".info-"+id).show(200); /* SHOW THE INFO OF THE SELECTED FULL NAME */
});
</script>
This is just a simple trick. But I think it is better than doing an Ajax call from every select of full_name.
Establish your connection to your database using mysqli_* extension also:
$connection = new mysqli("Host", "User", "Password", "Database");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

I ended up using an ajax call in the link to grab the delete page in the background to avoid the http redirect that was already setup and causing the issue.

Related

my data isnt inserting into mySQL data table with php

I need help on my code. When data is entered on my site, it does not show up in the mySQL data table. The insert function that I used might be the problem, but I cannot figure out how to get it to actually insert and show up in my table in my database. Can someone please guide me in the right direction with my code?
<?php
session_start();
include("db_connect.php");
if(isset($_POST['submit'])){
$item = $_POST['item'];
if(empty($item)) {
$errors = "you must enter something";
}
else{
mysqli_query("INSERT INTO a4_todolist (item) VALUES ('$item')");
header('location: index.php');
}
}
$a4_todolist = mysqli_query("SELECT * FROM a4_todolist");
?>
<!DOCTYPE html>
<html>
<head>
<title> Assignment 4 - To Do List </title>
<link rel ="stylesheet" type ="text/css" href="style.css">
</head>
<body>
<div class "head">
<h2> To Do </h2>
</div>
<form method= "POST" action = "index.php">
<?php if (isset($errors)) { ?>
<p><?php echo $errors; ?></p>
<?php } ?>
Item <input type = "text" name= "item" class="item_input">
Author <input type = "text" name= "author" class="author_input">
<button type = "submit" class="add-btn" name="submit"> Add Task
</button>
</form>
<table>
<tbody>
<?php while ($row = mysqli_fetch_array($a4_todolist)) { ?>
<tr>
<td class="id"> <?php print $row['id']; ?> </td>
<td class="item"> <?php echo $row['item']; ?> </td>
</tr>
<?php } ?>
</tbody>
</table>
</thread>
</body>
</html>
You have missed the sql connection variable which is coming from db_connect.php file inside your mysqli_query. Your mysqli_query() should be like this
mysqli_query($connection,"INSERT INTO a4_todolist (item) VALUES ('$item')");
Also this
$a4_todolist = mysqli_query($connection,"SELECT * FROM a4_todolist");
It seems that you are a beginner so I recommend you to learn Prepared statements which is more efficient and safe to use.
You should pass the connection link identifier as well as you can check for errors.
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Also after executing query you can again check for error.
if (!mysqli_query($con,"INSERT INTO a4_todolist (item) VALUES ('$item')")) {
echo("Error description: " . mysqli_error($con));
}

Why is the last iteration given, instead of the current one?

I have some PHP & HTML code which fetches id's, names & statuses from a mysql database.
Using buttons and $_POST i'm attempting to update the MYSQL database when said the users button is clicked (it's a simple in/out board)
Here is my code
<?php
include 'confile.php';
if(isset($_POST['update'])) {
echo $_POST['update']. " "; //test to show correct name
echo $_POST['staffid']; //test to show the correct staffid << **THIS IS WHERE THE ISSUE IS**
//$incid = $_POST['staffid'];
//$sql = "SELECT status FROM staff WHERE id=$incid";
//$result = $conn->query($sql);
//echo $result; //show the status
} else {
//do nothing.
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Staff Board</title>
<body>
<div align="center" class="header">
<div class="header text">
<h1>Staff Board</h1>
</div>
<div class="header logo">
<img src="/assets/img/logo.gif" width="64px" height="64px">
</div>
</div>
<div id="conbox" align="center" class="content">
<hr>
<?php
//get all staff and their statuses
$sql = "SELECT id, firstname, surname, status FROM $staff ORDER BY surname ASC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
// assign results to values
$id = $row["id"];
$firstname = $row["firstname"];
$surname = $row["surname"];
$status = $row["status"];
$fullname = $firstname . " " . $surname . " " . $id; //The $id variable will be dropped from here... it's just for testing. note, it works here, the correct ID is added to the button value
if ($status == 1) { //pick the correct color for the status
$color = "butGreen";
} else {
$color = "butRed";
}
?>
<form class="staffGrid" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<input type="hidden" id="staffid" name="staffid" value="<?php echo htmlspecialchars($id); ?>"/> <!-- hidden input to pass the id to $_POST -->
<input type="submit" id="update" name="update" value="<?php echo htmlspecialchars($fullname); ?>"/> <!-- submit button to trigger POST -->
</form> <!-- added as per devpro & billyonecan -->
<?php
};
?>
</div>
</div>
</body>
</html>
When I first load the page, the buttons show correctly, and there is no test output at the top of the page, which I expect.
however, when I click a button, the page refreshes correctly, and shows the correct name for the button being pushed (from the echo on line 5), but the wrong staffid is given. It gives the LAST id for the while loop, instead of correct value for that button.
I had assumed that for each iteration, the values would be set for that specific element (the button)... obviously i'm incorrect here.
Why is this happening and how do I fix it?
Additional info
Confile.php has the following variables used in the code:-
$conn = new mysqli($server, $username, $password);
$staff = [Location of db table]
some output :-
echo $sql;
SELECT id, firstname, surname, status FROM inout.staff ORDER BY surname ASC
echo print_r($_POST);
Array ( [staffid] => 17 [update] => First Second 8 )
The solution was to ensure that the closing tag was present in the code, and in the correct location to prevent erroneous iteration!

How to loop through results of a mysql query and display them in option values in an html form

How can I loop through results of a MySQL query and display them in option values in the html form in my script.
I have tried putting the values manually into the option tags and values, but I want to do it depending on whats already inside the database. Do I need another connection to the database to run in the same part as the form element itself?
<title>Add a unit</title>
</head>
<body>
<div class= "container">
<h1>Add a unit</h1>
<?php // Script 12.4 - add_size.php
// This script adds a blog size to the database.
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle the form.
// Connect and select:
$connection = mysqli_connect('localhost', $user, $password, $database);
mysqli_set_charset($connection, 'utf8');
// Validate the form data:
$problem = false;
if (!empty($_POST['unit']) && !empty($_POST['size']) && !empty($_POST['price'] && isset($_POST['building'])) {
$unit = mysqli_real_escape_string($connection, trim(strip_tags($_POST['unit'])));
$size = mysqli_real_escape_string($connection, trim(strip_tags($_POST['size'])));
$price = mysqli_real_escape_string($connection, trim(strip_tags($_POST['price'])));
$building = mysqli_real_escape_string($connection, trim(strip_tags($_POST['building'])));
} else {
echo '<p style="color: red;">Please submit a unit and an size and price.</p>';
}
if (!$problem) {
// Define the query:
$query = "INSERT INTO individualspecs (Space, Size, Price, fk_Id, Id) VALUES ('${unit}', '${size}', '${price}', '${building}', 0)";
// Execute the query:
if (#mysqli_query($connection, $query)) {
echo '<p>The unit has been added!</p>';
// why doesnt print "$msg"; work when using $i
} else {
echo '<p style="color: red;">Could not add the unit because:<br>'.mysqli_error($connection).'.</p><p>The query being run was: '.$query.'</p>';
echo $msg;
}
mysqli_close($connection); // Close the connection.
} // No problem!
} // End of form submission IF.
// Display the form:
?>
<form action="add_units.php" method="post" enctype="multipart/form-data">
<p>Select Building: <select name="building">
<option value="<?php echo ?>"><?php echo ?></option>
<option value=""></option>
<option value=""></option>
<option value=""></option>
</select>
</p>
<p>Enter Unit: <input type="text" name="unit" size="40" maxsize="100"></p>
<p>Enter Size in Sq Feet: <input type="number" name="size" size="40" maxsize="100"></p>
<p>Enter Price: <input type="text" name="price" size="40" maxsize="100"></p>
<!-- removed upload photos -->
<input type="submit" name="submit" value="Add indiviual Space!">
</form>
</div>
</body>
</html>
I would like the select dropdown menu to show a list of all buildings currently in the database so that the user can select a building to add his unit to.
If no buildings exist in database handle situation i.e. echo 'No buildings found in database, you need to
add a building record before attempting to add individual units';
Here is my buildings table:
https://imgur.com/a/2KMOUBD
Here is my units table:
https://imgur.com/a/w24IFuy
Here's a simple code to do what you need
Your code is so messed up, try to clean it :-)
We connect to mysql DB Using PDO class because it's more powerful and secure
you can change root with your db username
pass with your db password
db with your db name
read more about PDO here
// connect to db
$dbh = new \PDO('mysql:host=127.0.0.1;dbname=db', "root", "pass");
// query to select from db
$q = 'SELECT * FROM users';
// prepare and execute the query
$buildsq = $dbh->prepare($q);
$buildsq->execute();
// fetch the results and save them to $build var
$builds = $buildsq->fetchAll();
// check if their is results and print them
if($buildsq->rowCount()) {
foreach ($builds as $build) {
echo '<option value="">' . $build['name'] . '</option>';
}
} else {
echo "<option>No results </option>";
}
It's not the best, but it does what you need.
Try to put connection part in a function to clean up your code.

Not get mysql db data .... into html page with php (stumped)

I am working on an assignment, and it requires me to select a "slip_id" from the 3aStudent_Slip.php and pass it to 4aservice_request.php and populate a table that is being built in the php code. I have NOT had any php classes so I am really struggling with why it's NOT getting any database from the "ProgrammingDatabase" on the server.
Using the following code ...
<?php
require_once('auth.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Service Requests</title>
<link href="loginmodule.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="innerWrapper">
<h1>Service request by <?php echo $_SESSION['SESS_FIRST_NAME'];?></h1>
Login Page |
Menu Page |
Logout
<?php
$slip_id = strtoupper($_POST['slip_id']);
echo("<h2>Services for Slip ID $slip_id</h2>");
//Verify Password
$vlogin=$_SESSION['vlogin'];
$vpassword=$_SESSION['vpasswd'];
//Connection String
$con=mysql_connect("localhost", $vlogin, $vpasswd);
if(!$con)
{
die("Could not connect".mysql_error());
}
//Select Database
mysql_select_db("ProgrammingDatabase", $con);
//The actual SQL code goes below into the structured variable $result
$result=mysql_query("SELECT * FROM service_request");
//Constructing the table and column names
echo "<table border='1'>
<tr>
<th>Service ID</th>
<th>Description</th>
</tr>";
//Looping until there are no more records from $result
//If there are records, print the column for that row
//do the while loop below with the variables from $result
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row['service_id']."</td>";
echo "<td>".$row['description']."</td>";
echo "</tr>";
}
echo "</table>";
//Close the SQL connection string
mysql_close($con);
?>
<br />
<form action="a4Services_Student.php " method="post">
<br />
</form>
</div>
</body>
</html>
As some of the comments have already stated, the function you are using is not safe and is also depreciated.
The best way is to use PDO.
I have an example of it here https://snippetbox.xyz/5c3db100112bca204643/
<?php
/** How to get information out a database securely **/
$id = 6; // example value
//connect to mysql database using pdo
$conn = new PDO('mysql:host=localhost;dbname=someDatabase', $username, $password);
$query = "SELECT * FROM myTable WHERE id = :id";
//prepare the statement to avoid sql injection
$stmt = $conn->prepare($query);
//load variable into the statement and execute
$stmt->execute(array('id' => $id));
//fetch the results
$rows = $stmt->fetchAll(PDO::FETCH_OBJ);
//loop through all the lines
foreach ($rows as $row){
//loop through results here
//example
//echo $row->value;
}
?>

$_POST not passing correctly to mysqli query (no error and I see my value passes through but will not bind)

Okay so I have this really simple form that looks up values in my db tables. I haven't fully completed it yet and I was chugging along okay until I wanted to use a Jquery datepicker(I want to be able to easily select within a large custom set of years).
Due to my own reasons, the tables on my db don't use total date values so I split up the value into strings to lookup (worked fine with html5, but its not seeming to work with jquery)
Well, now I get "Call to a member function data_seek() on a non-object in" on my code. I've been tearing it apart and trying to fix things for several hours now and I kindly seek your help SO community:
Here is the PHP code:
<?php
$estring = substr($_POST[idvalue],-10, 5);
$wstring = substr($_POST[idvalue],6);
$mysqli = mysqli_connect("localhost", "usr", "", "xyz");
echo $estring."<br>";
echo $wstring;
$stmt = $mysqli->prepare('SELECT * FROM western WHERE id = ?');
$stmt->bind_param('s', $wstring);
$stmt->execute();
while ($row = $stmt->fetch()) {
echo "sign: ". $row['Western Zodiac Description']."<br>";
echo " Birth Card: = " . $row['Birth Card'];
echo " : =" . $row['Birth Card Descripton']."<br>";
echo "Planetary Card =". $row['Planatray Card'];
echo " : ". $row['Planatary Card Description']."<br>";
echo " 2nd Planetary Card =". $row['2nd Planatray Card'];
echo ": " . $row['2nd Planatary Card Description']."<br>";
}
$mysqli->close();
?>
Here is the frontend HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>project </title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#datepicker" ).datepicker({
yearRange: "1645:2112",
changeMonth: true,
changeYear: true
});
});
</script>
</head>
<body>
<br>
<form action="outputb.php" method="post">
enter date: <input type="text" id="datepicker" name='idvalue'>
<br>
<br>
<input type="submit" value="Search"/>
</form>
</body>
</html>
First change mysqli connection to
$mysqli = new mysqli("localhost", "usrnm", "xxxyz", "db");
if ($mysqli->connect_errno) {
die( $mysqli->connect_error);
}
Then change query string
$query = "SELECT * FROM western WHERE id IS '$wstring'";
To
$query = "SELECT * FROM western WHERE id = '$wstring'";
Also add error reporting ($mysqli->error) and final suggestion:
if ($res = $mysqli->query($query)){
//$res->data_seek(0);
if ($res->num_rows == 0){ // use if required
echo 'no data found!';
}
while ($row = $res->fetch_assoc()){
echo "sign: ". $row['Western Zodiac Description']."<br>";
echo " Birth Card: = " . $row['Birth Card'];
echo " : =" . $row['Birth Card Descripton']."<br>";
echo "Planetary Card =". $row['Planatray Card'];
echo " : ". $row['Planatary Card Description']."<br>";
echo " 2nd Planetary Card =". $row['2nd Planatray Card'];
echo ": " . $row['2nd Planatary Card Description']."<br>";
}
echo 'DEBUG OUTPUT <br>';
echo $estring."<br>";
echo $wstring;
$mysqli->close();
}else{
die($mysqli->error);
}

Categories