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;
}
?>
Related
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.
Right now I'm trying to create a PHP/MySQL setup that adds a name to a database. I don't want it to add the name to the database if it already exists though. Right now it is adding the name to the database regardless.
I have three files that I use for this.
First is the Names.php file:
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>About</h1>
<form action="Insert.php" method="post">
<p>What is your full name?</p><input type="text" name="names"><br>
<input type="submit">
</form>
<?php include("Footer.php");?>
</div>
</body>
</html>
Next is the Insert.php file:
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
mysql_select_db("a7068104_world") or die("Cannot connect to database");
$result = mysql_query("SELECT * FROM names_1 ORDER BY names");
if(!$result) {
die('Invalid SELECT query:' .mysql_error());
}
$sql="INSERT INTO names_1 (names) VALUES ('$_POST[names]')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
header("refresh:1.5; url=NamesAction.php");
mysql_close($con)
?>
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<p>You will be redirected back to the <b>Names</b> page in a moment.</p>
<?php include("Footer.php");?>
</div>
</body>
</html>
And lastly there is the NamesAction.php file:
<html>
<head>
<link rel="stylesheet" href="Site.css">
<?php include("Header.php"); ?>
</div>
</head>
<body>
<div id="main">
<h1>Names</h1>
<?php
$con = mysql_connect("localhost","a7068104_user2","wiseguy1345");
if(!$con) {
die("could not connect to localhost:" .mysql_error());
}
mysql_select_db("a7068104_world") or die("Cannot connect to database");
?>
<?php
mysql_query("LOCK TABLES names_1 WRITE;");
$result = mysql_query("SELECT * FROM names_1 ORDER BY names DESC LIMIT 100000");
if(!$result) {
die('Invalid SELECT query:' .mysql_error());
}
echo "<table border='2'>
<tr>
<th>Name</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['names'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_query("UNLOCK TABLES;");
mysql_close($con);
?>
<?php include("Footer.php");?>
</div>
</body>
</html>
Please help as I have no idea how to make sure that I don't enter something into the database twice! What I want to do is check the database to make sure it isn't added already, if it is added already send a message to the user and do add it, and if it isn't added already send a message saying it is adding to the database and add it to the database.
Thanks,
leonardude
First of all don't use mysql_* series of functions. But I'm gonna write the following code using them since you are probably more used to them. But seriously, don't use them. Instead use mysqli or PDO.
$name = mysql_real_escape_string($_POST['names']);
$query = "SELECT * FROM names_1 WHERE names='$name'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
//Already in Db
}
else{
$query = "INSERT INTO names_1 (names) VALUES('$name')";
$result = mysql_query($query);
if($result){
//successful
}
else{
//Unsuccessful
}
}
Or just let the database engine handle the task for you by adding a unique constraint to the columns that are to be unique as other answers suggested.
Use the UNIQUE key.
CREATE TABLE someTable(
ID INT PRIMARY KEY,
some_unique_value INT UNIQUE
);
I hope this helps :)
Create unique key for fields you need to be unique in database and try/catch thrown exception when duplicate data is entered.
This check may be done on the database side
ALTER TABLE `names_1`.`names` DROP PRIMARY KEY, ADD PRIMARY KEY (`names`);
I am just building a simple search page in PHP. I need to know how can i keep the selecte value of the drop down list upon form submission. Currently, the value resets to the first index.
Can I do this via PHP without using client-side script?
Here is the code:
<?php
mysql_connect('localhost','root','');
mysql_select_db('hotel');
$sql = "SELECT * FROM customers";
$result = mysql_query($sql);
?>
<!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>
</head>
<body>
<form method="get">
<select name="field" id="field">
<?php
/*if($field == 'Active')
'selected="selected"';
*/
while($rows = mysql_fetch_array($result))
echo '<option>'.$rows['customer_id'].'</option><br>';
?>
</select>
<?php
if (isset($_GET['Search']) && $_GET['action']=='search')
{
$sql="SELECT * FROM customers WHERE customer_id=".$_GET['field'];
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo '<br>Customer Name: '.$row['customer_name'].'<br>';
echo 'Email Address: '.$row['Email_Addr'].'<br>';
echo 'Contact No: '.$row['Contact_No'].'<br>';
}
?>
<input type="hidden" name="action" value="search" />
<br><input type="submit" value="search" name="Search" onclick="" />
</form>
</body>
</html>
usually like this.
echo '<option';
if ($_GET['field'] == $rows['customer_id']) echo " selected";
echo '>'.$rows['customer_id'].'</option>';
And please don't use the mysql_* functions to write new code, especially when you are learning. The mysql_* functions are in the process of becoming deprecated, they will be removed in future versions of PHP. Use mysqli_* or PDO objects instead.
You can check if the get value is the same than the select value :
while($rows = mysql_fetch_array($result))
echo '<option value="'.$rows['customer_id'].'" '.($rows['customer_id'] == $_GET['field']?'selected="selected"':'').'>'.$rows['customer_id'].'</option><br>';
When printing the select options, you can check for the value and set any mathing option to selected, maybe like this:
while($rows = mysql_fetch_array($result)){
if(!empty($_GET['field']) && $_GET['field'] == $rows['customer_id']){
echo '<option selected="selected">'.$rows['customer_id'].'</option><br>';
}
else {
echo '<option>'.$rows['customer_id'].'</option><br>';
}
}
I'm new to PHP and MySQL. I am trying to make a simple search form using which I would want to show the results from the database based on the input text entered in the form.
My code is like this:
Form.php
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<title>test</title>
</head>
<body>
<form action="search.php" method="GET" id="form">
Name: <input type="text" name="name" >
Age:<input type="text" name="age">
Search<input type="submit" name="submit" id="Search" Value="Search">
</form>
</body>
</html>
Connect.php
<?php
$connect = mysql_connect('localhost','$user','$password');
if(!$connect){
die('Could not connect'.mysql_error() );
}
$db_selected = mysql_select_db('test');
if(!$db_selected){
die('wrong'.mysql_error() );
}
?>
Search.php
<?php
include("includes/connect.php");
$name=$_GET['name'];
echo $name;
$query = "SELECT * FROM `cats` WHERE name='\$name'";
$results= mysql_query($query);
if (!empty($results)){
echo "query successful" ;
exit;
}
$row=mysql_fetch_assoc($results);
echo "Age:".$row['age'];
echo "Name:".$row['name'];
?>
The echo $names ouputs the result correctly and so does echo "query successful".
However the
echo "Age:".$row['age'];
echo "Name:".$row['name'];
only echo's the string part and the query does not seem to fetch any results.
I tried changing the mysql_fetch_assoc to mysql_fetch_array, but it does not do anything either. Could anyone tell me what am i doing wrong here. My DB table has two columns and two rows.
You're escaping the $ in the variable by doing \$.
Try:
$query = "SELECT * FROM `cats` WHERE name='$name'";
EDIT
From the discussion below.
The problem with the undefined index is the fact that you are using $row['age'] when really, the column name in the database is Age. Therefore you must use $row['Age'] when referring to the item. The same goes for name.
$query = "SELECT * FROM `cats` WHERE name='" . $name . "'";
or without concatenation
$query = "SELECT * FROM `cats` WHERE name='$name'";
This should work:
$query = "SELECT * FROM cats WHERE name = '$name'";
Also, when you call "exit;" in the following block it will cancel the execution of the rest of your script:
if (!empty($results)){
echo "query successful" ;
exit;
}
Hi I have a page that displays all of the contents of my table. Alongisde each row of the table I also have a column containing a checkbox. When the user selects one or more rows by ticking the checkbox and pressing the submit button, I want just those rows to appear in a table on the next page (buy.php). I know it is basically a select statement per row that is selected. But I dont know how to approach this. Can anybody help? Thanks
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Shopping</title>
</head>
<body>
<form action='buy.php' method='post'>
<input type='submit' value='Submit' />
</form>
<h1>Buy</h1>
<?php // Script 12.7 - sopping.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
$query = 'SELECT * FROM Items';
if ($r = mysql_query($query, $db)) {
print "<form>
<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
<td><input type='checkbox' name='buy[{$row['ID']}] value='buy' /></td>
</tr>";
}
print "</table>
</form>";
} else {
print '<p style="color: blue">Error!</p>';
}
mysql_close($db); // Close the connection.
?>
</body>
</html>
EDIT: I tried the suggestion below and I did not get a table. Just the title of the page appeard:
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Confirmation</title>
</head>
<body>
<h1>Order Details</h1>
<?php // Script 12.7 - buy.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
foreach($_POST['buy'] as $item) {
$query = 'SELECT * FROM Items WHERE ID = $item';
if ($r = mysql_query($query, $db)) {
print "<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
</tr>";
}
print "</table>";
} else {
print '<p style="color: blue">Error!</p>';
}
}
mysql_close($db);
?>
</body>
</html>
You need to create a dynamic SQL query.
1) I suggest you change your checkbox to the following
<input type='checkbox' name='buy[]' value='{$row['ID']}' />
2) Loop through all of the buy options
<?php
foreach($_POST['buy'] as $item) {
// Append the ID (in the $item variable) to the SQL query, using WHERE `ID` = $item OR `ID` = $item and so on
}
?>
UPDATE:
<?php // Script 12.7 - buy.php
$db = mysql_connect('localhost', '#####', '#####');
mysql_select_db('shopping', $db);
$query = 'SELECT * FROM Items WHERE ';
$item_count = count($_POST['buy']);
for($i = 0; $i < $item_count; $i++) {
$itemid = (int)mysql_real_escape_string($_POST['buy'][i]); // Secures It
$query .= '`ID` = '.$itemid;
if($i +1 < $item_count) {
$query .= ' OR ';
}
}
if ($r = mysql_query($query, $db)) {
print "<table>";
while ($row = mysql_fetch_array($r)) {
print
"<tr>
<td>{$row['ID']}</td>
<td>{$row['Name']}</td>
<td>{$row['Cost']}</td>
</tr>";
}
print "</table>";
mysql_close($db);
?>
// this checkbox use
//buy.php foreach($_POST['buy'] as $item) {
$query = "SELECT * FROM Items WHERE ID = $item"; //use " "
// try it if any problem please carefully look you database table // download file and try it 2file with table sql data
// https://copy.com/8ZsBAFj7LvypLJkK
// this checkbox use
<input type='checkbox' name='buy[]' value='{$row['ID']}' />
//buy.php
foreach($_POST['buy'] as $item) {
$query = "SELECT * FROM Items WHERE ID = $item";
//use " "
// try it if any problem please carefully look you database table
// download file and try it 2file with table sql data
// https://copy.com/8ZsBAFj7LvypLJkK