PHP- Unable to Access Data from DB in dropdown menu - php

I am trying to create a drop down menu that will display Project Names off all Projects present in the table Project in the database Testing... The drop down is created but it is not accessing the database and retrieving the required data...
The code is as follows:
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
Project List :
<select Project Name='NEW'>
<option value="">--- Select ---</option>
<?
$serverName = "Swagatha-PC";
$connectionInfo = array( "Database"=>"Testing");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
if (isset ($select)&&$select!="")
{
$select=$_POST ['NEW'];
}
?>
<?
$query=mysql_query("select ProjectName from dbo.Project");
$menu=" ";
while($row = sqlsrv_fetch_array($query))
{
$menu ="<option>" . $row["ProjectName"] . "</option>";
}
?>
</select>
<input type="submit" name="Next" value="Select" />
</form>
</body>
</html>
Dropdown Error
What Do i do to fix this??

The solution is
while($row = sqlsrv_fetch_array($query))
{
echo "<option>" . $row["ProjectName"] . "</option>";
}
See? You output data with echo instead assinging data to variable.
And as #FirstOne noticed using mysql_query with sqlsrv_connect is an error too. I hope it's just your typo:
$query=sqlsrv_query($conn, "select ProjectName from dbo.Project");
As another sidenote
if (isset ($select)&&$select!="")
{
$select=$_POST ['NEW'];
}
this if will always be false, because you first check $select and then define it. It definitely should be:
if (isset($_POST['NEW']) && $_POST['NEW'] != "")
{
$select = $_POST['NEW'];
}

Here is you fixed code. You can try it
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<form id="form1" name="form1" method="post" action="<?php echo $PHP_SELF; ?>">
Project List :
<select Project Name='NEW'>
<option value="">--- Select ---</option>
<?php
$serverName = "Swagatha-PC";
$connectionInfo = array( "Database"=>"Testing");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
if (isset ($select)&&$select!="")
{
$select=$_POST ['NEW'];
}
$query=sqlsrv_query("select ProjectName from dbo.Project");
$menu=" ";
while($row = sqlsrv_fetch_array($query))
{
echo "<option>" . $row["ProjectName"] . "</option>";
}
?>
</select>
<input type="submit" name="Next" value="Select" />
</form>
</body>
</html>

Related

SQL query using string concatenation

I am new to php and I have a table "abc" where I have columns: id, name and age.
I want to do the following:
Only if a name is entered in the input field, corresponding data (id and age) should be shown using string concatenation to build SQL query.
This is for search functionality
What should be the SQL query for this question?
// Create connection
$conn = new mysqli($SERVER_NAME, $USER_NAME, $PASSWORD, $DATABASE_NAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = " SELECT name, CONCAT(id,'.',age) FROM personene WHERE name = 'VALUE_FROM INPUT_NAME'";
$result = $conn->query($sql);
$error = mysqli_error($conn);
// Store results
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php if(!empty($error))
echo "<p style='color:red'>$error</p>";
?>
<p>Please enter the name:</p>
<form action="<?=$_SERVER['PHP_SELF']?>" method="GET">
<input type="input" name="name" value="" />
<br/>
<input type="submit" name="sendbtn" value="Send" />
</form>
<?php
if(!empty($data)) {
echo "<h1>Persons:</h1><table border='1'><tr><th>Id</th><th>Firstname</th><th>Age</th></tr>";
foreach($data as $row) {
echo "<tr><td>".$row["id"]."</td>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["age"]."</td></tr>";
}
echo "</table>";
}
else
echo "No data available";
echo '(Query: '.$sql.')';
?>
</body>
</html>
It is not clear why you want to concatenate fields in the SQL query when clearly in the html these fields are displayed in their own columns. The code you have is wide open to SQL Injection so you need to consider using a prepared statement to handle the user supplied input safely.
<?php
$data=[];
error_reporting( E_ALL );
if( $_SERVER['REQUEST_METHOD']=='GET' && !empty( $_GET['name'] ) ){
$SERVER_NAME='';
$USER_NAME='';
$PASSWORD='';
$DATABASE_NAME='';
mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
$conn=new mysqli( $SERVER_NAME, $USER_NAME, $PASSWORD, $DATABASE_NAME );
try{
$sql = 'select `name`, `id`, `age` from `personene` where `name` = ?';
$stmt=$conn->prepare( $sql );
$stmt->bind_param('s', $_GET['name'] );
$stmt->execute();
$stmt->bind_result( $name, $id, $age);
while( $stmt->fetch() )$data[]=[
'name' => $name,
'id' => $id,
'age' => $age
];
$stmt->free_result();
$stmt->close();
$conn->close();
}catch( mysqli_sql_exception $e ){
exit( $e->getMessage() );
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Fetch user details</title>
</head>
<body>
<p>Please enter the name:</p>
<form method='GET'>
<input type='input' name='name' />
<br/>
<input type='submit' name='sendbtn' value='Send' />
</form>
<?php
if( !empty( $data ) ) {
echo "
<h1>Persons:</h1>
<table border='1'>
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Age</th>
</tr>";
foreach( $data as $row ) {
echo "
<tr>
<td>{$row["id"]}</td>
<td>{$row["name"]}</td>
<td>{$row["age"]}</td>
</tr>";
}
echo "</table>";
} else {
echo "No data available";
}
?>
</body>
</html>
For the SQL query to find records related with name, you have to use this query,
select concat('id', '-', 'age') as user_data from abc where name = $REQUEST['search_name'];
OR you can use LIKE(check here) condition to get the records from the table.
select concat('id', '-', 'age') as user_data from abc where name like
$REQUEST['search_name'];
Here is an update for your code,
<?php
// Create connection
$conn = new mysqli($SERVER_NAME, $USER_NAME, $PASSWORD, $DATABASE_NAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// echo "Connected successfully";
$data = [];
$sql = "Please submit the form.";
if(isset($_GET['sendbtn']) ) {
$sql = " SELECT id, name, age FROM personene WHERE name = '". $_GET['name'] ."'";
$result = $conn->query($sql);
$error = mysqli_error($conn);
// Store results
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
if(!empty($error))
echo "<p style='color:red'>$error</p>";
?>
<p>Please enter the name:</p>
<form action="<?=$_SERVER['PHP_SELF']?>" method="GET">
<input type="input" name="name" value="" />
<br/>
<input type="submit" name="sendbtn" value="Send" />
</form>
<?php
if(isset($data) && !empty($data)) {
echo "<h1>Persons:</h1><table border='1'><tr><th>Id</th><th>Firstname</th><th>Age</th></tr>";
foreach($data as $row) {
echo "<tr><td>".$row["id"]."</td>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["age"]."</td></tr>";
}
echo "</table>";
} else {
echo "No data available";
}
echo '(Query: '.$sql.')';
?>
</body>
</html>

Passing a select value to Oracle database

I'm working on this code I used Oracle HR database as my database, I'm trying to filter database results based on multiple select, but I keep getting this error:
Warning: oci_execute(): ORA-00933
Warning: oci_fetch_array(): ORA-24374
and no results, my code:
index.php
<html>
<head>
<title>Employees Search</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function checkinput()
{
if(document.Form2.DEPARTMENT_ID.value=="" && document.Form2.MANAGER_ID.value=="")
{
alert("Please select department or manager!");
return;
}
document.Form2.submit();
}
</script>
</head>
<body>
<form method="get" name="Form2" id="Form2">
<select id="DEPARTMENT_ID" name="DEPARTMENT_ID">
<option value="">DEPARTMENT:</option>
<option value="90">90</option>
<option value="60">60</option>
<option value="100">100</option>
<option value="30">30</option>
</select>
<select id="MANAGER_ID" name="MANAGER_ID" >
<option value="">MANAGER ID:</option>
<option value="100">100</option>
<option value="102">102</option>
<option value="103">103</option>
<option value="108">108</option>
</select>
<input type="button" value=" Search " onclick="checkinput()" />
</form>
<br />
<div id="result">
<?php include "emp.php"; ?>
</div>
</body>
</html>
emp.php
<?php
$conn = oci_connect('hr', ' ', 'My-PC:1521/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
if(isset($_GET['DEPARTMENT_ID'])||isset($_GET['MANAGER_ID'])){
$DEPARTMENT_ID=$_GET['DEPARTMENT_ID'];
$MANAGER_ID=$_GET['MANAGER_ID'];
$sql="SELECT * FROM EMPLOYEES WHERE ";
if($DEPARTMENT_ID != "")
{
$sql = $sql."DEPARTMENT_ID=".$DEPARTMENT_ID;
if($MANAGER_ID != "")
{
$sql = $sql."MANAGER_ID=".$MANAGER_ID;
}
}
else
{
if($MANAGER_ID != "")
{
$sql = $sql."MANAGER_ID=".$MANAGER_ID;
}
}
$stid = oci_parse($conn, $sql);
oci_execute($stid);
echo " <table><tr><th>Employee No.</th><th>First Name</th><th>Last Name</th><th>PHONE NUMBER</th><th>Email</th><th>Job Title</th><th>MANAGER_ID</th><th>DEPARTMENT_ID</th></tr>";
while ($row = oci_fetch_array($stid, OCI_ASSOC )) {
echo "<tr>";
echo "<td>".$row['EMPLOYEE_ID']."</td>";
echo "<td>".$row['FIRST_NAME']."</td>";
echo "<td>".$row['LAST_NAME']."</td>";
echo "<td>".$row['PHONE_NUMBER']."</td>";
echo "<td>".$row['EMAIL']."</td>";
echo "<td>".$row['JOB_ID']."</td>";
echo "<td>".$row['MANAGER_ID']."</td>";
echo "<td>".$row['DEPARTMENT_ID']."</td>";
echo "</tr>";
echo"</table>";
}
}
?>
Everything seems correct expect SQL when Department and manager id is not null.
<?php
$conn = oci_connect('hr', ' ', 'My-PC:1521/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
if(isset($_GET['DEPARTMENT_ID'])||isset($_GET['MANAGER_ID'])){
$DEPARTMENT_ID=$_GET['DEPARTMENT_ID'];
$MANAGER_ID=$_GET['MANAGER_ID'];
$sql="SELECT * FROM EMPLOYEES WHERE ";
if($DEPARTMENT_ID != "")
{
$sql = $sql."DEPARTMENT_ID=".$DEPARTMENT_ID;
if($MANAGER_ID != "")
{
$sql = $sql."AND MANAGER_ID=".$MANAGER_ID;
}
}
else
{
if($MANAGER_ID != "")
{
$sql = $sql."MANAGER_ID=".$MANAGER_ID;
}
}
$stid = oci_parse($conn, $sql);
oci_execute($stid);
echo " <table><tr><th>Employee No.</th><th>First Name</th><th>Last Name</th><th>PHONE NUMBER</th><th>Email</th><th>Job Title</th><th>MANAGER_ID</th><th>DEPARTMENT_ID</th></tr>";
while ($row = oci_fetch_array($stid, OCI_ASSOC )) {
echo "<tr>";
echo "<td>".$row['EMPLOYEE_ID']."</td>";
echo "<td>".$row['FIRST_NAME']."</td>";
echo "<td>".$row['LAST_NAME']."</td>";
echo "<td>".$row['PHONE_NUMBER']."</td>";
echo "<td>".$row['EMAIL']."</td>";
echo "<td>".$row['JOB_ID']."</td>";
echo "<td>".$row['MANAGER_ID']."</td>";
echo "<td>".$row['DEPARTMENT_ID']."</td>";
echo "</tr>";
echo"</table>";
}
}
?>
Changed Line :
$sql = $sql."AND MANAGER_ID=".$MANAGER_ID;
May be reason as SQL failed to parse this query.
As If both are not empty and assumed 10 then you query will be looked like SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID=10 MANAGER_ID=10; which is not syntactically correct.

using a drop down menu to pull select query results into a form

I'm using a form to input new projects into my database. One of the fields is Lead Writer. I want to add a drop down menu to that field that will display the names of the lead writers from my database that the user can then select to populate that field. I've managed to get the drop down to appear in the field, but my code isn't generating any names. I tried setting up a function that would call those results, but it's obviously not working. The form worked well prior to my changes, so it's not an issue connecting to the database. Any help would be greatly appreciated.
function query(){
$myNames = "SElECT LastName FROM Projects";
$result = $mysqli->query($myNames);
while($result = mysqli_fetch_array($myNames)){
echo '<option value=' . $record['LastName'] . '>' . $record['LastName'] . '</option>';
}
}
?>
<?php
$connection->close();
?>
<form action="http://www.oldgamer60.com/Project/NewProject.php" method="post">
<div class="fieldset">
<fieldset>
Project: <input type="text" name="Project value="<?php if(isset($Project)){ echo $Project; } ?>">
<span class="error">* <?php if(isset($ProjectErr)){ echo $ProjectErr; } ?></span>
<br><br>
Client: <input type="text" name="Client" value="<?php if(isset($Client)){ echo $Client; } ?>">
<span class="error">* <?php if(isset($ClientErr)){ echo $ClientErr; } ?></span>
<br><br>
Lead Writer: <select name="dropdown">
<?php query() ?>
</select>
<br><br>
Date Received: <input type="text" name="DateReceived" value="<?php if(isset($DateReceived)){ echo $DateReceived; } ?>">
<span class="error">* <?php if(isset($DateReceivedErr)){ echo $DateReceivedErr; } ?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</div>
</form>
Edited Code:
<html>
<head>
</head>
<body>
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $mysqli->query($myNames)) {die($mysqli->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}
?>
<form>
Lead Writer: <select name="dropdown">
<?php query($mysqli); ?>
</select>
</form>
<?php
$connection->close();
?>
</body>
</html>
2nd Edit:
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
function query($connection){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $connection->query($myNames)) {die($mysqliconnection->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}?>
<?php
$connection->close();
?>
<form>
Lead Writer: <select name="dropdown">
<?php query($connection); ?>
</select>
</form>
</body>
</html>
You have a variable scope issue - http://php.net/manual/en/language.variables.scope.php. $mysqli is undefined in your function query(). You need to pass it as a param. Also, you were trying to do mysqli_fetch_array() on the query string, instead of the mysqli result. I have updated it to the OO ->fetch_array().
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
$result = $mysqli->query($myNames);
while($record = $result->fetch_array()){
echo '<option value=' . $record['LastName'] . '>' . $record['LastName'] . '</option>';
}
}
You will also need to pass it in your call
Lead Writer: <select name="dropdown">
<?php query($mysqli); ?>
</select>
You can add some debugging to find out why it is not printing
function query($mysqli){
$myNames = "SELECT LastName FROM Projects";
if(!$result = $mysqli->query($myNames)) {die($mysqli->error);} // check for error message
if($result->num_rows > 0){ // if there is rows
while($record = $result->fetch_array()){
echo '<option value="' . $record['LastName'] . '">' . $record['LastName'] . '</option>';
}
} else { // if there is no rows
echo '<option value="">No Rows</option>';
}
}
per your edit - https://stackoverflow.com/posts/34257335/revisions
Your mysqli connection is $connection
// create connection
$connection = new mysqli($servername, $username, $password, $dbname);
so not sure why you are trying to use $mysqli
$mysqli->query($myNames)
as $connection != $mysqli.
As you are doing the query in a function, you don't need to rename all instances of $mysqli to $connection, as you can just change to
Lead Writer: <select name="dropdown">
<?php query($connection); ?>
</select>

php code to take values from two forms and insert it in table

I have two forms on one page. First one take names of students according to group. Second form is used to enter marks individually. Now i want to insert their marks but failed to do this. Kindly help me regarding this. My code is:
$faculty = null; //declare vars
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Not connected : ' . mysql_error());
}
mysql_select_db('Sims', $link) or die("cannot select DB");
if(isset($_POST["faculty"]))
{
$faculty = $_POST["faculty"];
}
?>
<script language="JavaScript">
function autoSubmit()
{
var formObject = document.forms['theForm'];
formObject.submit();
}
</script>
<form name="theForm" method="post">
<select name="faculty" onChange="autoSubmit();">
<option value="null"></option>
<option value="computer" <?php if($faculty == 'computer') echo " selected"; ?>>Computer</option>
<option value="commerce" <?php if($faculty == 'commerce') echo " selected"; ?>>Commerce</option>
</select>
<br><br>
<?php
if($faculty =='computer')
{
echo "<select name=\"name\">";
$sql = mysql_query("SELECT name FROM std_reg where faculty= 'computer' ") or die(mysql_error());
while($row = mysql_fetch_array($sql)){
echo "<option>".$row[name]."</option>";}
echo "</select>";
}
if($faculty =='commerce')
{
echo "<select name=\"name\">";
$sql = mysql_query("SELECT name FROM std_reg where faculty= 'commerce' ") or die(mysql_error());
while($row = mysql_fetch_array($sql)){
echo "<option>".$row[name]."</option>";}
echo "</select>";
}
?>
<br><br>
</form>
<form method="post">
math <input type="text" name="urdu" />
science <input type="text" name="science" />
social <input type="text" name="social" />
submit
</form>

Turning a mysql column into an array and using the array in a dropdown

Long time listener, first time caller. I'm having trouble with pulling a column called "Rep_IP" from a mysql table called "roster", turning it into an array, and then using that array to populate a dropdown in html. I've tried several suggestions listed here as well as other places and I'm not having any luck. The page shows up just fine but the dropdown has no options to select. I figured I would see if one of you could tell me what I am doing wrong here.
<html>
<body>
<form action="insert.php" method="post">
<p>Rep ID:</p>
<?php
$con = mysql_connect("localhost", "root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("rep_stats", $con);
$query = "SELECT Rep_ID FROM roster";
$result = mysql_query($query) or die ("no query");
$result_array = array();
echo "$query"
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
?>
<select name="Rep_ID">
<?php
foreach($result_array as $rep)
{
echo "<option value=" . $rep['Rep_ID'] . ">" . $rep['Rep_ID'] . "</option>";
}
?>
</select>
Issues Handled: <input type="number" name="IssuesHandled">
Hours Worked: <input type="number" step="any" name="HoursWorked">
<input type="submit">
</form>
</body>
</html>
As you can see, the drop down is part of a form that is used to create an entry in a new table as well. I don't know if that makes a difference but I figured I would point it out.
Try this.
<select name="Rep_ID">
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<option value=" . $row['Rep_ID'] . ">" . $row['Rep_ID'] . "</option>";
}
?>
</select>
Try this:
<?php
function select_list(){
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link)
{
echo ('Could not connect');
}
ELSE {
$query = "SELECT Rep_ID FROM roster";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<option value=" . $row['Rep_ID'] . ">" . $row['Rep_ID'] . "</option>";
}
}
mysqli_close($link);
}
$begin_form =
<<< EODBEGINFORM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Insert data </title></head>
<body>
<form action="insert.php" method="post" name="form1">
<p>Rep ID:</p>
<select name="reps" form="form1">
EODBEGINFORM;
$end_form =
<<< EODENDFORM
</select><br>
Issues Handled: <input type="text" size="12" name="IssuesHandled"><br>
Hours Worked: <input type="text" size="12" name="HoursWorked"><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
EODENDFORM;
echo $begin_form;
echo select_list();
echo $end_form;
?>
You will notice that I have used MYSQLI_ istead of MYSQL_ the reason is that this better for new code, see the comments above.
I debugged your code and ran I to a lot of problems.:-( The main problem was:
echo "$query" Your forgot the semicolon at the end of the line.
Good luck with you project.

Categories