No data displayed from DB in drop down menu - php

Echo 'Hello programmers' ;
I'm scratching my head about a pair of drop down menus. They are supposed to display all strings from the ename and mid rows. However this isn't happening and the drop down is only displaying one result from each row. There are multiple strings of test data in the actual rows.
I have some code here and perhaps you could lend a hand. Let me explain.
First off these are the methods from class dbme. To keep the clutter down the second function is exactly the same, except the SQL query for getResult() is obviously different (SELECT * from member as opposed to memberevent)
function openDB() {//creating database connection
$conn = mysqli_connect("localhost", "root", "", "mydb");
if (!$conn) {
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
function getResult($sql){
$result = mysqli_query($this->conn , "SELECT * from memberevent" );
if ($result) {
return $result;
} else {
die("SQL Retrieve Error: " . mysqli_error($this->conn));
}
}
Second, this is the web-side data.
$db1 = new dbme();
$db1->openDB();
$sql="select mid from member";
$result=$db1->getResult($sql);// get the ids from the tables for the select
$sql1="select ename from event";
$result1=$db1->getResult($sql1);// get the ids from the tables for the select
if (!$_POST) //page loads for the first time
{
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" onsubmit="return validateForm( );">
Select Member ID: <select name="mid">
<?php
while($row = mysqli_fetch_assoc($result))
echo "<option value='{$row['mid']}'>{$row['mid']} </option>";
?>
</select>
<br />
Select Event name : <select name="ename">
<?php
while($row = mysqli_fetch_assoc($result1))
echo "<option value='{$row['ename']}'>{$row['ename']} </option>";
?>
</select>
<br />
I have a sneaking suspicion that a variable is getting over written, OR an extra loop is needed somewhere. But I'm not really sure, thus I post this question for advice.
Thanks.

You need to iterate through your results inside your getResults() function, otherwise you will always only get one row.

You are passing in the SQL but never using it:
Change
function getResult($sql){
$result = mysqli_query($this->conn , "SELECT * from memberevent" );
To
function getResult($sql){
$result = mysqli_query($this->conn , $sql );

Related

Select data from MySQL DB based on the URL example (www.example.co.uk/essex.php)

I am very new to php and I am looking to create dynamic pages.
Basically If a person lands on www.example.co.uk/essex.php I would like to be able to add something like <h1>Company In <?php echo $row['County']; ?> so that it would show
Company In Essex when Live and save time if I need to duplicate the page for another county or town.
So far I have setup a database in phpmyadmin
Picture of Table
My code so far to grab the table is;
$dbconnect = mysqli_connect("HOST", "USER", "PASSWORD", "DB");
if(mysqli_connect_errno()) {
echo "Connection Failed:".mysqli_connect_error();
exit;
}
$count_sql="SELECT * FROM areas";
$count_query=mysqli_query($dbconnect, $count_sql);
$count_rs=mysqli_fetch_assoc($count_query);
and then on www.example.co.uk/essex.php
<?php
do {
echo $count_rs['County'];
} while ($count_rs=mysqli_fetch_assoc($count_query))
?>
But where I have gone wrong is it pulls all the data from the table for County where I only wish it to pull the county of Essex.
Please forgive me for explaining this badly.
UPDATE -
$row = url2content();
extract($row);
function url2content($url = NULL){
if(is_null($url)){
if(isset($_SERVER["REQUEST_URI"]) && $_SERVER["REQUEST_URI"]){
$url = $_SERVER["REQUEST_URI"];
}elseif(isset($_SERVER["PATH_INFO"]) && $_SERVER["PATH_INFO"]){
$url = $_SERVER["PATH_INFO"];
}
if (substr($url,0,1) == '/'){
$url = substr($url,1);
}
}
if (DEBUG_MODE){
echo ('URL requested: "'.$url.'"<br>');
}
function get_towns($county){
$query = sprintf("select townName from " . AREAS_TABLE . " where countyName = '%s' order by rand() LIMIT 0,24" ,mysql_real_escape_string($county));
$res = mysql_query($query);
if(!$res){
printf("Unable to query ".AREAS_TABLE." table: %s \n", mysql_error());
}
$html="";
while($row = mysql_fetch_assoc($res)){
$html.="<li>".stripslashes($row["townName"])."</li>\n";
}
return $html;
}}
You have to use WHERE clause in your query in order to select a specific country from your db
SELECT * from table WHERE felid_country=$count_rs['County'];
You can use strpos() to match the County (eg.essex) with url $_SERVER['REQUEST_URI'] (eg.www.example.co.uk/essex.php) in your case.
Just like this
<?php
do {
if(strpos($_SERVER['REQUEST_URI'],$count_rs['County'])!=false)
echo $count_rs['County'];
} while ($count_rs=mysqli_fetch_assoc($count_query))

Populate drop down using PHP ODBC function

Can you help me tracing my problem on populating drop down menu using ODBC Function in PHP. Here's my code:
$conn = $conn = odbc_connect("mm370lib", "ictapps", "s3cur3344");
if(! $conn){
print( "Cannot connect to database" );
exit;
}
$qry1 = "SELECT * FROM APSUPP";
//$res = odbc_do($conn, $qry);
$res1 = odbc_exec($conn, $qry1);
echo "<select class='form-control' name='vendor_name'>";
while($row1 = odbc_fetch_row($res1)){
echo "<option value='".$row1["ASNUM"]."'>".$row1["ASNAME"]."</option>";
}
odbc_free_result($res1);
echo "</select>";
It is not showing the fetch data from database.
See attached file
According to the doc, odbc_fetch_row() does not return a row, but just true or false, indicating if a row was fetched. See here for more information: http://php.net/manual/en/function.odbc-fetch-row.php
So, following the doc, you need to call odbc_result() after you've fetched a row. See here for more info: http://php.net/manual/en/function.odbc-result.php
It should probably be something like this (I do not have a php environment here right now, so this code is untested):
while(odbc_fetch_row($res1))
{
$asnum = odbc_result($res1, "ASNUM");
$asname = odbc_result($res1, "ASNAME");
echo "<option value='".$asnum."'>".$asname."</option>";
}

having trouble getting selected value from php dynamic selection option

I want to show options from my database for users to check, but having trouble getting user's choice.
So, I write two php files,
the first one doing things like: getting data from database, displaying in select option, then submit value by post to and the second php file.
And the second php file just display the recieved value.
Here's the first php file:
<html>
<body>
<form method="post" action="second.php">
<Select name=”select_value”>
<?
//connect to server
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Error " . mysqli_error($con));
$query = "SELECT * FROM MYTABLE" or die("Error in the consult.." . mysqli_error($con));
$result = $con->query($query);
//display result in select option
while ($row = mysqli_fetch_array($result)) {
echo "<Option value=".$row['ENTRY_ID']."> ".$row['ENTRY_NAME']."</Option><br>";
}
mysqli_close($con);
?>
</Select>
</form>
</body>
</html>
And the second php file:
<?
$option = isset($_POST['select_value']) ? $_POST['select_value'] : false;
if($option) {
echo $_POST['select_value'];
} else {
echo "not getting value of select option";
exit;
}
?>
If this works fine, I should see the selected value by the second php file, but I keep recieving my echo "not getting value of select option".
There must be something wrong between select option and my recieving file.
Can someone help?
try this double quotes
<Select name="select_value">
instead of <Select name=”select_value”>

Issue deleting rows in SQL of type varchar

I am trying to create a form that will delete a row in a table based on the attribute a user selects from a drop down list of options. For some reason the first option, (attemptid) which is an int, works, but the other three (which are varchar) do not. The error handling I have set up to debug the script is returning 1 or true, but the row in question is not deleted.
HELP! I have tried everything but am only just learning PHP so imagine I am missing something quite simple.
require_once("settings.php");
$conn = #mysqli_connect($host, $user, $pass, $db);
if ($conn) {
?>
<form method="post" action="delete_attempts.php" name="delete_attempts" id="delete_attempts" >
<label for="deleteby">
<p>Select an option to delete results by:</p>
</label>
<select name="deleteby">
<option value="attemptid">Attempt ID</option>
<option value="firstname">First Name</option>
<option value="lastname">Last Name</option>
<option value="studentid">Student ID</option>
</select>
<p></p>
<input type="text" name="delvalue" placeholder="Value">
<div>
<input type="submit" value="Delete Record" id="submit" />
</div>
</form>
<?php
if (isset($_POST["delvalue"])) {
// get value from form
$delValue = trim($_POST["delvalue"]);
echo $delValue;
// queries to delete record
$queryAttemptId = "DELETE FROM quizattempts WHERE attemptid = '$delValue'";
$queryFirstName = "DELETE FROM quizattempts WHERE firstname = '$delValue'";
$queryLastName = "DELETE FROM quizattempts WHERE lastname = '$delValue'";
$queryStudentId = "DELETE FROM quizattempts WHERE studentid = '$delValue'";
//select which value to search for
if ($_POST["deleteby"] = "attemptid") {
// pass query to database
$result = mysqli_query($conn, $queryAttemptId);
} // end delete attemptid
else if ($_POST["deleteby"] = "firstname") {
// pass query to database
$result = mysqli_query($conn, $queryFirstName);
} // end delete firstname
else if ($_POST["deleteby"] = "lastname") {
// pass query to database
$result = mysqli_query($conn, $queryLastName);
} // end delete lastname
else if ($_POST["deleteby"] = "studentid") {
// pass query to database
$result = mysqli_query($conn, $queryStudentId);
} // end delete student id
echo "this is the result $result";
// if query is successful are found
if ($result) {
echo "<p>Delete operation successful</p>";
} // end if result found
else {
// if no record is found in DB
echo "<p>No records found</p>";
} // end if no result found
} //isset($_POST["attemptid"])
} //$conn
?>
if ($_POST["deleteby"] = "attemptid") {
That should be ==. Your code as written will assign "attemptid" to $_POST["deleteby"] and then return the same value... which is always true. So your other else ifs are never even checked.
Also, your code as written is vulnerable to SQL injection. You're already using mysqli; you should strongly consider using prepared statements.

SQL Query results into dropdown list

I am trying to get the names of the events from a table in a database, i need to insert this data in a dropdown list, so then someone clicks them and then the information for this specific event displays...
Here is my code up to now..
<?php
require "config.php"; // Your Database details
?>
<?PHP
$SQL = "SELECT title_en_US FROM civicrm_event";
$result = mysql_query($SQL);
// Write out our query.
$query = "SELECT title_en_US FROM civicrm_event";
// Execute it, or return the error message if there's a problem.
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['title_en_US'] . "<BR>";
}
?>
Can you tell me how to put first the event names into a dropdown list?
Thanks!
Please use the following code
$options='';
while($db_field = mysql_fetch_assoc($result))
{
$options .= "<option>".$db_field['title_en_US']."</option>";
}
For the html part,
<select name="titles"><? echo $options; ?></select>

Categories