PHP PDO Crud advice - php

I have just started to learn PDO and have managed to do simple CRUD operations on one single table.
I am just doing a SELECT * from the table. But this table has a foreign key to another table, and I would rather show the value on that column instead of a ID.
So my table structure is the following. I have a joke table with id and joketext and a foreign key authorId. The author table has authorId and name for the author.
Instead of doing SELECT * on the joke table, I would rather create a view with the following code:
SELECT
joke.joketext,
author.name
FROM
author
INNER JOIN joke
ON author.id = joke.authorid
But for the CRUD operations I would like to show the author.name in a dropdown instead, so the users don't erroneously put in wrong values.
This is how index.php looks like:
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
$result = $dbConn->query("SELECT * FROM joke ORDER BY id DESC");
?>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Joke</td>
<td>AuthorId</td>
<td>Update</td>
</tr>
<?php
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td>".$row['joketext']."</td>";
echo "<td>".$row['authorid']."</td>";
echo "<td>Edit | Delete</td>";
}
?>
</table>
and my edit file looks like this:
<?php
// including the database connection file
include_once("config.php");
if(isset($_POST['update']))
{
$id = $_POST['id'];
$name=$_POST['joketext'];
$authorid=$_POST['authorid'];
// checking empty fields
if(empty($joketext) || empty($authorid)) {
if(empty($joketext)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($authorid)) {
echo "<font color='red'>Author field is empty.</font><br/>";
}
} else {
//updating the table
$sql = "UPDATE joke SET joke=:joketext, authorid=:authorid WHERE id=:id";
$query = $dbConn->prepare($sql);
$query->bindparam(':id', $id);
$query->bindparam(':joketext', $joketext);
$query->bindparam(':authorid', $authorid);
$query->execute();
// Alternative to above bindparam and execute
// $query->execute(array(':id' => $id, ':name' => $name, ':email' => $email, ':age' => $age));
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
?>
<?php
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$sql = "SELECT * FROM joke WHERE id=:id";
$query = $dbConn->prepare($sql);
$query->execute(array(':id' => $id));
while($row = $query->fetch(PDO::FETCH_ASSOC))
{
$joketext = $row['joketext'];
$authorid = $row['authorid'];
}
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
Home
<br/><br/>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>Joke</td>
<td><input type="text" name="joketext" value="<?php echo $joketext;?>"></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" name="authorid" value="<?php echo $authorid;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
Can someone show me a hint on at least the edit operations how the php code would like?
thanks

If you wish to provide a select element of available authors for the user to choose from on the edit page, rather than have them enter an ID number for an author, then you can select all the authors from the database and loop through them, building the options of your select element. A select element can show the user the name of the author, but pass the ID of the author back to the server. You can also pre-select an author to show the user the currently associated author by default and they only have to change it if it's wrong.
So first, select all the authors from the database:
$authorSql = 'SELECT * FROM author';
$authorQuery = $dbConn->prepare($authorSql);
$authorQuery->execute();
Then use that data to build a select element:
<select name="authorid">
<?php
while($author = $authorQuery->fetch(PDO::FETCH_ASSOC)) {
if ($author['id'] == $authorid) {
//The author is currently associated to the joke, select it by default
echo "<option value=\"{$author['id']}\" selected>{$author['name']}</option>";
} else {
//The author is not currently associated to the joke
echo "<option value=\"{$author['id']}\">{$author['name']}</option>";
}
}
?>
</select>
The output might look something like this:
<select name="authorid">
<option value="1">George Carlin</option>
<option value="2" selected>Richard Pryor</option>
<option value="3">Don Rickles</option>
</select>
Whatever option the user selects, they'll see on the page what is between the <option></option> tags, but the form will pass the value of the value property to the server as the authorid parameter.
The code that generates the select element replaces the <input type="text" name="authorid" value="<?php echo $authorid;?>"> and remains within the <td></td> tags.
Hope I managed to address your actual need, let me know if I missed the intent of your question.
Note: my code isn't tested, so some adjustment may be required.
EDIT #1: Fixed incorrect variable names.

Related

Why does my PHP/Oracle Update query simply refresh the data when I click on Update

I'm working on a page which allows the user to update the RESULT data field for a specified row within my database on Oracle SQL Developer. I have the code set up in a table structure which allows the user to highlight which specific row of data they would like to edit and save their changes to.
The issue I am now facing in regards to this however is when I click on the "Update" button on the actual page view, the data simply refreshes to it's original condition.
(E.g I change contents of the field from Pass to Fail > Click Update > Field refreshes with Pass back in that specific field.)
I'm unsure in this scenario what it is I am exactly doing wrong, because I've defined my UPDATE query and I've references it in the table structure.
My Code
<!DOCTYPE HTML>
<html>
<head>
<title> Objective </title>
</head>
<body>
<?php
if(isset($_POST['update'])){
$UpdateQuery = "UPDATE OBJECTIVE SET RESULT='{$_POST['Result']}' WHERE OBJECTIVE_ID='{$_POST['hidden']}'";
oci_parse($conn, $UpdateQuery);
}
?>
<?php
$sql = 'SELECT * FROM OBJECTIVE';
$stid = oci_parse($conn, $sql);
oci_execute($stid);
?>
<div>
<table border='1'>
<tr>
<th>Objective ID</th>
<th>Objective Type</th>
<th>Description</th>
<th>Result</th>
<th>Mission_ID</th>
<tr>
<?php
while($row= oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
?>
<tr>
<form method = "POST" action="">
<td><?php echo $row ['OBJECTIVE_ID']?> </td>
<td><?php echo $row['OBJECTIVE_TYPE']?></td>
<td><?php echo $row['DESCRIPTION']?></td>
<td><input type ="text" name="Result" value="<?php echo $row['RESULT'];?>"/></td>
<td><?php echo $row['MISSION_ID']?></td>
<td><input type="hidden" name="hidden" value="<?php echo $row['OBJECTIVE_ID']; ?>" readonly/></td>
<td><input type="submit" name="update" value="Update" /></td>
</form>
<tr>
<?php }?>
</div>
</body>
</html>
I am aware of SQL Injections, they are not a concern currently cause the app is only planned to be used on my own server which I myself am the only person whop has access to.
You are parsing the update but not executing it...
if(isset($_POST['update'])){
$UpdateQuery = "UPDATE OBJECTIVE SET RESULT='{$_POST['Result']}' WHERE OBJECTIVE_ID='{$_POST['hidden']}'";
$stid = oci_parse($conn, $UpdateQuery);
oci_execute($stid);
}
I would look into prepared statements and binds even if using a local machine.

PHP MySQL Get the value of a dynamic select

I have a table item (id, name, content, categories id (foreign key table category)) and a category table (id, title)
name: type text
content: textarea
categories_id: select dynamics related to the category table
Inserting the item table that works very well but in the modification. I have a problem with the dynamic select to the list of categories, not pick me a choice that I chose to add a article.
How I can get the value of the select tag? <select> <option></option> </select>
<?php
include 'dbconnect.php';
$id = $_GET['id'];
$sql = mysql_query("SELECT * FROM articles WHERE id ='".$id."'");
$res = mysql_fetch_assoc($sql);
if (#$_REQUEST['do'] == "update") {
$m_id = $_POST['id'];
$nom = $_POST["nom"];
$contenu = $_POST["contenu"];
$categories_id = $_POST["categories_id"];
$sql = mysql_query("UPDATE articles SET nom='$nom', contenu='$contenu', categories_id='$categories_id' WHERE id =' $m_id' ");
if($sql)
header("Location:listArticles.php");
else
header("Location:updateArticle.php");
}
?>
<html lang="en">
<body class="nav-md">
<?php if (isset($_GET['id']) && $_GET['id'] == $id) { ?>
<form action="" method="post" accept-charset="utf-8">
<table>
<td>Nom: <input type ="text" name ="nom" value="<?php echo $res['nom'] ?>"></td>
</br>
<td>Contenu: <textarea name ="contenu"><?php echo $res['contenu'] ?></textarea></td>
</br>
<td>
Categories:
<select class="form-control" name="categories_id" value="<?php echo $res['categories_id'] ?>" >
<option></option>
</select>
</td>
<td>
<button type="submit" class="btn btn-success" name ="do" value="update">Modifier</button>
</td>
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
</table>
</form>
<?php } ?>
</body>
</html>
That is what the page currently looks like:
If I understand you correctly (and judging by the picture), you want to show the categories and select the category associated with the article.
Here's a rough, untested sketch of how you can approach. Read my comments also.
<?php
include 'dbconnect.php';
// assuming ID is integer, we'll use intval()
$id = isset($_GET['id']) ? intval($_GET['id']) : null;
// query article matching given ID
$articleRes = mysql_query("SELECT * FROM articles WHERE id ='" . $id . "'");
$article = mysql_fetch_assoc($articleRes);
// query categories
$categoriesRes = mysql_query("SELECT * FROM categories");
// check if form has been submitted
// if you are expecting POST, use $_POST not $_REQUEST
// don't use #, it's sloppy
if (!empty($_POST['do'])) {
$m_id = $_POST['id'];
$nom = $_POST["nom"];
$contenu = $_POST["contenu"];
$categories_id = $_POST["categories_id"];
// update article with given ID
// is it nom or name?
$updateRes = mysql_query("UPDATE articles SET nom='$nom', contenu='$contenu', categories_id='$categories_id' WHERE id='$m_id'");
if ($updateRes) {
header("Location: listArticles.php");
} else {
header("Location: updateArticle.php");
}
// good practice to die after you redirect
die();
}
?>
<html lang="en">
<body class="nav-md">
<?php if ($article) : ?>
<form action="" method="post" accept-charset="utf-8">
<table>
<td>Nom: <input type="text" name="nom" value="<?php echo $article['nom'] ?>"></td>
<!-- you cannot have a BR tag in between TD tags -->
<!--/br-->
<td>Contenu: <textarea name="contenu"><?php echo $article['contenu'] ?></textarea></td>
<!-- you cannot have a BR tag in between TD tags -->
<!--/br-->
<td>
Categories:
<!-- SELECT tag does not have a VALUE attribute -->
<select class="form-control" name="categories_id">
<!-- loop through the categories and build the OPTION tag -->
<!-- for each iteration, check if the category ID matches the article's category ID -->
<!-- if so, mark the option as selected -->
<?php while ($category = mysql_fetch_assoc($categoriesRes)) : ?>
<option <?php echo $category['id'] == $article['categories_id'] ? 'selected' : '' ?>><?php echo $category['title'] ?></option>
<?php endwhile ?>
</select>
</td>
<td>
<!-- unnecessary to have VALUE attribute as this element will always be submitted -->
<button type="submit" class="btn btn-success" name="do">Modifier</button>
</td>
<input type="hidden" name="id" value="<?php echo $article['id'] ?>">
</table>
</form>
<?php endif ?>
</body>
</html>
Additional points:
Stop using mysql_* functions! They are deprecated for good reasons. Use mysqli_* or better PDO functions.
Your queries are prone to SQL injection.
When mixing PHP control structures (e.g. if, while, etc) with HTML, I like to use their alternative syntax (e.g. if (condition): and endif; while (condition): and endwhile; etc). It looks more readable, imo.
I am using the ternary operator which is a shorter syntax for simple if/else statements.
Add comments!
Update your update query:
$sql = mysql_query("UPDATE articles SET nom='$nom', contenu='$contenu', categories_id='$categories_id' WHERE id ='$m_id' ");
For suggestion:
use mysqli_() as mysql_ are depreciated please follow the link: Why shouldn't I use mysql_* functions in PHP?
take care of sql injection
don't suppress the warning using (#)

calculate student total marks and insert that total in another table with the id of that student together

I'm developing a simple student information system, for now i have 300 students and six subjects, so when i want to add marks obtained by each student i use html form and php script to add those marks, for each student i add marks for six subjects that is one subject at a time, so i'm asking if there is the way where by php can allow me retrieve one student and add all the marks for the six subjects at once and then take another and so on. Also i want to calculate total marks for each student and store those total in another table with respective student id so that i can know who is the first student and who is the last by using that total marks of each student.
here is the way i'm doing right now
<?php error_reporting(E_ALL ^ E_NOTICE); ?>
<html>
<body>
<div>
<div>
<form action="connmarks.php" method="post">
<table>
<tr><td colspan="6"> </td></tr>
<tr><td><p>Adding Student Results</p></td></tr>
<tr>
<td width="9%">Student Code<?php echo $mstudentcode;?></td>
<td width="17%"><input name="student_code" type="text" size="30" value="<?php echo $studentcode;?>" /></td></tr>
<tr>
<td width="10%">Subject Code<?php echo $msubjectcode;?></td>
<td width="18%"><input name="subject_code" type="text" size="30" value="<?php echo $subject_code;?>"/></td></tr>
<tr>
<td width="12%">Marks<?php echo $mmark;?></td>
<td width="34%"><input name="mark" type="text" size="30" value="<?php echo $mark;?>"/></td>
</tr>
<td> </td>
<td>
</td>
</tr>
<tr><td colspan="4"> </td></tr>
<tr><td colspan="6"> </td></tr>
<tr>
<td> </td><td colspan="6"><input type="submit" name="save" value="Add Marks" /></td>
</tr>
<tr><td colspan="6"><?php echo $sms1.$sms.$sms2;?></td></tr>
</table>
</form>
</div>
<div id="footer">Copyright <?php echo date("Y", time()); ?></div>
</div>
</body>
</html>
<?php error_reporting(E_ALL ^ E_NOTICE); ?>
<?php
session_start();
if(isset($_POST['save']))
{
// validating student code
if(empty($_POST['student_code']))
{
$mstudentcode='<font color="red"><b>**</b></font>';
}
else
{
$student_code=$_POST['student_code'];
}
// validation for kiswahili subject
if(empty($_POST['subject_code']))
{
$msubjectcode='<font color="red"><b>**</b></font>';
}
else
{
$subject_code=$_POST['subject_code'];
}
// validating english subject
if(empty($_POST['mark']))
{
$mmark='<font color="red"><b>**</b></font>';
}
else
{
$mark=$_POST['mark'];
}
// checking if there is any error message, if no error proceed, if there is error, display the error
// Then exit the script and redirect at the same page
if($mstudentcode||$msubjectcode||$mmark||$sms)
{
$sms1='<font color="red"><b>Error found,please check **</b></font><br/>';
include 'addmarks.php';
exit;
}
// if there is no error include connection file
if($student_code&&$subject_code&&$mark)
{
// include 'mysqli_connect.php';
require_once ('../../mysqli_connect.php');
$addmarks= "insert into result(student_code,subject_code,mark) values ('".$student_code."','".$subject_code."','".$mark."')";
$k = mysqli_query($dbc, $addmarks);
if ($k)
{
$sms1='<font color="green"><b>Student Marks Submitted Successfully</b></font><br/>';
include 'addmarks.php';
exit;
}
else
{
$sms1='<font color="red"><b>Failed To Add Student Marks</b></font><br/>';
include 'addmarks.php';
exit;
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post">
<!-- Displays all users in database in a select option -->
<select name="students">
<option>Student 1</option>
<option>Student 2</option>
<?php
//This code below is what you will need to use for yours to pull values out of the database(changing the values to suit yours obviously).
// $query = "SELECT * FROM students ORDER BY student_name ASC";
// $result = mysqli_query($conn,"$query");
// while($row = mysqli_fetch_assoc($result)){
// echo "<option>" . $row['student_name'] . "<br></option>";
// }
?>
</select><br>
<!-- All the different input fields for maths, english and science -->
<input type="text" name="eng_grade" value="" placeholder="Enter English Grade"><br>
<input type="text" name="math_grade" value="" placeholder="Enter Maths Grade"><br>
<input type="text" name="science_grade" value="" placeholder="Enter Science Grade"><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
//If submit is pressed
if (isset($_POST['submit'])) {
//this gets the value of the student name from the select box and stores it as $student
$student = $_POST['students'];
//These gets the values stored in the inputs above and store them in the 3 vairables
$english = $_POST['eng_grade'];
$maths = $_POST['math_grade'];
$science = $_POST['science_grade'];
//this is a mysql query that updates the data with whatever you put into the database(to add to existing tables you will have to dig abit deeper and create your
//database with all the correct fields!
$query = "UPDATE students SET maths_grade = '$maths', $english_grade = '$english', science_grade = '$science' WHERE student_name = '$student'";
$update = mysqli_query($conn, "$query"); //<-- this inserts the values into the database, changing the current #null value (null means nothing is in it)
}
?>
</body>
</html>
Create 2 tables, one for student and other for marks.
In one table, just insert student name and id(unique), and in other table student all 6 subject marks i.e. 6 columns for 6 sub, 1 for student id, and other one as auto increment id column.
So using that student id you can retrieve all the subject marks of a particular student.
Edit: Just noticed this question is 3 years old w00t!?
Drafting tables would be something like
student table:
id primarykey integer
name notnullable nvarchar(255)
subject table
id primarykey integer
name notnullable nvarchar(255)
student_subject table
id primarykey integer
student_id foreignkey notnullable unique integer
subject_id foreignkey notnullable unique integer
mark notnullable double(2,2)
E.g. Select the marks of a subject
Select student.name, subject.name, subject_student.mark from subject_student
inner join student on student.id = subject_student.student_id
inner join subjecton subject.id = subject_student.subject_id
where student_id = X; // X is the id of the student you want
Any calculation should be based on query, you don't want to store results in the database. You want data in the database and since it's volatil data (can be changed anytime), it's easier and faster to calculate whenever required. Sum, GroupBy, there are a ton of basic sql keywords that can help you. student_subject table is the table where it combines that Many students in Many subjects with a certain mark. If you want to save a student's mark, you just Insert into this table the id's and the mark value.
Since it's a school project, this should be suffice for you to work it out.
In the future, take a look at prepared statements
http://php.net/manual/en/book.pdo.php

edit button to mysql

I got my database to work, and I can add my data and get return on it again. That is perfect, because it is the first time that I get it to work, and it opend up a lot of possibilies. So my next project here, is to ALTER my table in MySQL with a button. Until now it looks like this:
I can add a date, day, fromtime and totime. But I would like to have the possibility to change fx the day, if I make a mistake when I add the values to my database. I started on making an edit button in the right hand side. So overtime I make a new row, there will come a new edit button. But does anybody know how I can asign my button to the ALTER TABLE query? Or maybe a hint how to do it?
Best Regards to all
From Mads
EDITED CODE:
I have made the primary key in the database p_id. I also get a return from the p_id
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/arrangeTables.css">
</head>
<body>
<form method="post">
<h3>Add your worktime to database</h3><br>
<input type="date" name="date"><br><br>
<select name="day">
<option value="Mandag">Mandag</option>
<option value="Tirsdag">Tirsdag</option>
<option value="Onsdag">Onsdag</option>
<option value="Torsdag">Torsdag</option>
<option value="Fredag">Fredag</option>
<option value="Lørdag">Lørdag</option>
<option value="Søndag">Søndag</option>
</select>
<input type="time" name="fromtime">
<input type="time" name="totime">
<input type="submit" value="submit"><br><br>
</form>
</body>
<?php
$username = "root";
$password = "root";
$hostname = "127.0.0.1:3306";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br><br>";
//select a database to work with
$selected = mysql_select_db("danskebank",$dbhandle)
or die("Could not select any database");
// Insert to database
$date = $_POST['date'];
$day = $_POST['day'];
$fromtime = $_POST['fromtime'];
$totime = $_POST['totime'];
$sql = "INSERT INTO addWorkTime(date, day, fromtime, totime) VALUES('$date', '$day', '$fromtime', 'totime')";
$result = mysql_query($sql);
//Return records from database
$result = mysql_query("SELECT date, day, fromtime, totime FROM addWorkTime");
?>
<!-- Return from the database -->
<h3>Return from database:</h3><br>
<!-- headers -->
<tr>
<th class="column1">Date</th>
<th class="column2">Day</th>
<th class="column3">From</th>
<th class="column4">To</th>
</tr>
<!-- Now a row for each new set of data, here you probably need to
loop through some data set you retrieve from the database -->
<?php while($row = mysql_fetch_array($result)): ?>
<table>
<tr>
<td class="resultcolumn4"><?php echo $row{'p_id'};?></td>
<td class="resultcolumn1"><?php echo $row{'date'};?><br></td>
<td class="resultcolumn2"><?php echo $row{'day'};?></td>
<td class="resultcolumn3"><?php echo $row{'fromtime'};?></td>
<td class="resultcolumn4"><?php echo $row{'totime'};?></td>
<td><a href='link_to_the_add_or_edit?id='.<?php $row['id'] ?></td>
<?php
$id=$_GET['id'];
echo '<input type="hidden" name="name_of_hidden_input" value='.$id.'>';
//and the rest of the form
if($_GET['submit']){
//Some mysql injection prevention first
update danskebank SET date=['?'] where id= $_GET['name_of_hidden_input']
}
?>
</tr>
<?php endwhile; ?>
</table>
</html>
To edit the specific row, you would need a Primary key in your mysql table. For example you call it: id. Now you would need to get the id from the table as well: SELECT id, date, day, fromtime, totime FROM addWorkTime
Use the $row['id']; in the while loop and replace the : <input type="button" value="Edit"> to: <a href='link_to_the_add_or_edit?id='.<?php $row['id'] ?> now your url will look like: link_to_the_add_or_edit?id=1 and you can use: $_GET['id'] on the link_to_the_add_or_edit page. Now when you're on that page, you make sure you remember that id(SESSIONS) so you can use it on the submit action when you fill in the values.
Example of session:
session_start();
$_SESSION['id']=$_GET['id'];
on the link_to_the_add_or_edit page. After this you can update the row you want like this(when you submit something):
update danskebank SET date=['?'] where id= $_SESSION['id']
EDIT(regarding DarkBee's comment):
Instead of using sessions here, you can also store the $_GET['id'] in a hidden field like this:
$id=$_GET['id'];
echo '<input type="hidden" name="name_of_hidden_input" value='.$id.'>';
//and the rest of the form
if($_GET['submit']){
//Some mysql injection prevention first
update danskebank SET date=['?'] where id= $_GET['name_of_hidden_input']
}
and in the query use: $_GET['name_of_hidden_input'];
If you want to edit the values of the row try via url:
echo '<a href="edit.php?row_id=' . $row_id . '>Edit</a>'; //You should have id for every row
Create edit.php file and get row's id with $_GET['row_id']. Create form Add some input in it (like this one:<input type="datetime" />), and then handle it with another php file. You should execute your UPDATE query there. Like this :
$sql = "UPDATE row SET
date = '$date' ,
day = '$day' ,
fromtime = '$fromtime' ,
totime = '$totime'
WHERE id = $row_id;
";
mysql_query($sql);
But for all these you should have id for every row in the database.

How retrieve specific data from database mysql

I have a search.php in this I'm searching for three fields:
Form no.
Name
Telephone no.
But when I select a From no., from select option and enter in input a Telephone no. and press the search button it search for telephone no. instead of form no.
I want a search like when I select From no. and enter a value of than it should search only for form no nothing else and like all below two option:
serach.php
<div class="tleft">
<h2 class="tdilouge">Search Reports</h2><center>
<table class="tbleft">
<form action="searchbyform.php" method="get">
<thead>
<tr>
<td>
<select name="formnumber" id="formnumber" >
<option>Form No.</option>
<option>Name</option>
<option>Telephone No.</option>
</select>
</td>
<td><input type="text" name="formnumber" id="formnumber" placeholder="Enter" /></td>
<td><input type="submit" value="Search" /></td>
</tr>
</thead>
</form>
</table></center>
</div>
And this is submit.php I have a proper connection of database and column is table name:
submit.php
<?php
$formnumber = $_GET['formnumber'];
$sql = "SELECT * FROM colomn WHERE FormNo = $formnumber OR ConsumerName = $formnumber OR TelephoneNo = $formnumber";
$query = mysql_query( $sql );
if(mysql_num_rows($query) == 0)
{
echo "no result found";
}
echo "<table>";
echo "<thead></thead>";
while( $row = mysql_fetch_array( $query ) )
{
echo "<tr></tr>";
}
echo "</table>";
?>
You could just check which option the person has selected and depending on that selected option you could run the query that belong to that option.
Give the options a value, like this:
(You should change the select name because the textfield is already named formnumber)
<select name="form" id="form" >
<option value="form">Form No.</option>
<option value="name">Name</option>
<option value="telephone">Telephone No.</option>
</select>
So when you choose the option form no. , $_GET['form'] would be "form"
So just use an IF to check the 3 options.
EDIT:
The query when the Form no. has been chosen, will look like this:
"SELECT * FROM colomn WHERE FormNo = $formnumber"
And for the name and telephone no. You should just change the column name.
if($_get['form']="form"){
$sql="SELECT * FROM colomn WHERE FormNo = $formnumber";
}
if($_get['form']="name"){
$sql="SELECT * FROM colomn WHERE ConsumerName = $formnumber";
}
if($_get['form']="telephone"){
$sql="SELECT * FROM colomn WHERE TelephoneNo = $formnumber";
}
Also dont use mysql. Use mysqli or PDO instead.

Categories