filling in form fields from previous database entry - php - php

I am trying to create a form where everything is filled out from the user's previous entry. Its suppose to work by the user selecting the "update" link. However the form is not being filled at all.
I've been trying to figure this out for 2 days now but i cant seem to figure it out. Some help would be greatly appreciated, thanks!
up.php
<form method="POST" action="up1.php">
<?php
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp ORDER BY primeID DESC ";
$sql_result = mysql_query($sql1) or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
}
?>
Update
</form>
up1.php
<form action="up2.php" method="post">
<?
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp WHERE primeID = '$up22'";
$sql_result = mysql_query($sql1)
or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
$a1 = $row["country"];
$a2 = $row["job"];
$a3 = $row["pos_type"];
$a4 = $row["location"];
$a5 = $row["des"];
$a6 = $row["des_mess"];
$a7 = $row["blurb"];
$a8 = $row["restitle"];
$a9 = $row["res"];
$a10 = $row["knowtitle"];
$a11 = $row["know"];
$a12 = $row["mis"];
$a13 = $row["mis_des"];
}
?>
<input name="aa1" value="<? echo $a1; ?>" type="text" id="textfield" size="60">
<input name="a1" type="text" value="<? echo $a2; ?>" id="textfield" size="60">
<input name="a2" type="text" value="<? echo $a3; ?>" id="a2" size="60">
<input name="a4" type="text" value="<? echo $a5; ?>" id="a4" size="60">
</form>

Based upon the limited information I could get out of your post I think I found the problem:
Starting with up.php
Update
Actually sends a "GET request" (Loading the page with a query string). We need to rebuild that:
<a href="JavaScript: void(0)" onclick="this.parentElement.submit()" >Update</a>
Now this link is going to send the form. However we need to send the value $prime. Let's use a hidden input inside the form.
<input type="hidden" name="up22" value="<? echo $prime; ?>" />
Now when the user clicks the link it posts the form and loads up1.php with the post var up22.
Changes to up1.php
$sql1 = "SELECT * FROM emp WHERE primeID = '".$_POST['up22']".'";
PDO
To update your code even further: PDO is a safer way to do queries. mysql queries are deprecated. They shouldn't be used anymore.
Replace your database calls with the following code:
function openDBConnection()
{
$name = "xxxxxx";
$pw = "xxxxxx";
$server = "xxxxxxx";
$dbConn = new PDO("mysql:host=$server;dbname=xxx", $name, $pw, , array( PDO::ATTR_PERSISTENT => false));
}
catch( PDOException $Exception )
{
echo "120001 Unable to connect to database.";
}
return $dbConn;
}
function doPDOQuery($sql, $type, $var = array())
{
$db = openDBConnection();
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($type == "prepare")
{
$queryArray = $var;
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArray);
}
else if ($type == "query")
{
$sth = $db->query($sql);
}
else
{
echo "Supplied type is not valid.";
exit;
}
if (!$sth)
{
$error = $db->errorInfo();
echo $error;
exit;
}
return $sth;
}
These functions you can use to make PDO queries to the database. The first function opens a database connection, while the second functions actually performs the query. You do not need to call the first function. It's called in the second one.
Example based upon your code:
$sql1 = "SELECT * FROM emp WHERE primeID = :id";
$sql_result = doPDOQuery($sql1, 'prepare', array(":id" => $_POST['up22']));
while ($row = $sql_result->fetchAll() )
{
//loop through the results.
}
PDO works as follows: instead of passing php variables into the SQL string (and risking SQL-injection), PDO passes the SQL string and variables to the database and let's the database's driver build the query string.
PDO variables can be declared by name or by index:
By name: use : to declare a named variable. SELECT * FROM TABLE WHERE id = :id. Each key must be unique.
By index: use ? to declare an indexed variable. SELECT * FROM TABLE WHERE id = ?
An array containing the variables needs to be passed to PDO.
named array:
array(":id" => 1);
indexed array:
array(1);
With named arrays you don't have to worry about the order of the variables.
http://php.net/manual/en/book.pdo.php

Related

Switched computers and get two new mysqli_fetch_row errors.

after I managed to connect my website form to my database, I decided to try to transfer over my files to my work computer.
Initially I only had one error: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in...
However now I get an extra mysqli_fetch_row() error the same as above but the error is on a different line.
Additionally I also get the error: Undefined index: fill which I never got before. Are there any mistakes in my code? The form still works and can connect to my database.
<center><form action="fill.php" method="post">
Fill
<input type="text" id="fill"" name="fill">
<input type="submit" id ="submit" name="submit" value="Submit here!">
</form></center>
</div>
<?php
$val1 = $_POST['fill'];
$conn = mysqli_connect('localhost', 'root', '')or
die("Could not connect");
mysqli_select_db($conn, 'rfid');
$val2 = "SELECT * FROM card_refill WHERE refill = $val1";
$result1= $conn->query($val2);
$row = mysqli_fetch_row($result1);
$refill1 = $row[2];
$value = "SELECT *FROM card_credit ORDER BY id DESC LIMIT 1:";
$result = $conn->query($value);
$row = mysqli_fetch_row($result);
$refill = $row[2];
$money= $refill+$refill1;
echo $money;
$sql = "UPDATE card_credit SET value = '$money'";
if ($conn->query($sql) === TRUE) {
echo "Success";
}
else {
echo "Warning: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
</body>
</html>
You're getting that error because you use $_POST['fill'] without checking whether it's set first. It will only be set when the form is submitted, not when the form is first displayed. You need to put all the code that processes the form input into:
if (isset($_POST['submit'])) {
...
}
BTW, you can do that entire update in a single query.
UPDATE card_credit AS cc
CROSS JOIN card_refill AS cr
CROSS JOIN (SELECT * FROM card_credit ORDER BY id DESC LIMIT 1) AS cc1
SET cc.value = cr.col2 + cc1.col2
WHERE cr.refill = '$val1'
Like GolezTrol said from his comment. You're mixing object and functional notation.
Although this might not work exactly how you need it to because I don't have all the information. I have written you something I think is close to what you're looking for.
<?php
// Define the below connections via $username = ""; EXTRA....
// This is best done in a separate file.
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$val1 = $_POST['fill'];
$result1 = $conn->query("SELECT * FROM card_refill WHERE refill = '$val1' ");
$result2 = $conn->query("SELECT * FROM card_credit ORDER BY id DESC LIMIT 1:");
$refill1 = array(); // Pass Results1 Into Array
while($row = $result1->fetch_assoc()) {
$refill1[] = $row[2];
}
$refill = array(); // Pass Results2 Into Array
while($row = $result2->fetch_assoc()) {
$refill[] = $row[2];
}
/* Without an example of what data you are getting from your tables you will have to figure out what data you want from the arrays.
$money= $refill+$refill1;
echo "DEBUG: $money";
*/
// This code will not be functional until your populate the $money value.
$sql = "UPDATE card_credit SET value = '$money' ";
if ($conn->query($sql) === TRUE) {
echo nl2br("Record updated successfully"); // DEBUG
print_r(array_values($refill1)); // DEBUG
print_r(array_values($refill)); // DEBUG
echo nl2br("\n"); // DEBUG
} else { // DEBUG
echo "Error updating record: " . $conn->error; // DEBUG
echo nl2br("\n"); // DEBUG
}
$conn->close();
?>

Updating a single MySQL row

I have a table displaying the content of a MySQL table. For every row I added an 'edit button' so our users can update the content.
The 'edit button' goes to a link ?edit_entry.php?sid=4 with 4 the sid of the entry.
This works but I get a blank form.
Question 1: Is there any way to already display the content of the specific MySQL row in the text fields of the form?
Here is the edit_entry.php code:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
// Create connection
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sid = $_GET['sid'];
$sql = "SELECT * FROM orders WHERE sid = '$sid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = mysqli_fetch_array($sql)) {
$sid = $row['sid'];
$q1_requested_by = $row['q1_requested_by'];
$q2_productname = $row['q2_productname'];
$q3_supplier = $row['q3_supplier'];
$q4_productnumber = $row['q4_productnumber'];
$q5_quantity = $row['q5_quantity'];
$q6_price = $row['q6_price'];
$q7_budget = $row['q7_budget'];
$q8_link = $row['q8_link'];
}
?>
<form action="update_script.php" method="post">
<input type="hidden" name="sid" value="<?=$sid;?>">
Requested by: <input id="q1" type="text" style="width:400px" name="ud_q1_requested_by" value="<?=$q1_requested_by?>" required="true" tabindex="1"><br>
Product name: <input id="q2" type="text" style="width:400px" name="ud_q2_productname" value="<?=$q2_productname?>" required="true" tabindex="2"><br>
Supplier: <input id="q3" type="text" style="width:400px" name="ud_q3_supplier" value="<?=$q3_supplier?>" required="true" tabindex="3"><br>
Product number: <input id="q4" type="text" style="width:400px" name="ud_q4_productnumber" value="<?=$q4_productnumber?>" required="true" tabindex="4"><br>
Quantity: <input id="q5" type="text" style="width:400px" name="ud_q5_quantity" value="<?=$q5_quantity?>" required="true" tabindex="5"><br>
Price: <input id="q6" type="text" style="width:400px" name="ud_q6_price" value="<?=$q6_price?>" tabindex="6"><br>
Budget: <input id="q7" type="text" style="width:400px" name="ud_q7_budget" value="<?=$q7_budget?>" tabindex="7"><br>
Link: <input id="q8" type="text" style="width:400px" name="ud_q8_link" value="<?=$q8_link?>" tabindex="8"><br>
<input type="submit" name="submit" id="submit" value="Update your input!" tabindex="9" />
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
And here is update_script.php:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
// Create connection
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sid = $_POST["sid"];
$ud_q1_requested_by = mysqli_real_escape_string($_POST["ud_q1_requested_by"]);
$ud_q2_productname = mysqli_real_escape_string($_POST["ud_q2_productname"]);
$ud_q3_supplier = mysqli_real_escape_string($_POST["ud_q3_supplier"]);
$ud_q4_productnumber = mysqli_real_escape_string($_POST["ud_q4_productnumber"]);
$ud_q5_quantity = mysqli_real_escape_string($_POST["ud_q5_quantity"]);
$ud_q6_price = mysqli_real_escape_string($_POST["ud_q6_price"]);
$ud_q7_budget = mysqli_real_escape_string($_POST["ud_q7_budget"]);
$ud_q8_link = mysqli_real_escape_string($_POST["ud_q8_link"]);
$sql= "UPDATE orders
SET q1_requested_by = '$ud_q1_requested_by', q2_productname = '$ud_q2_productname', ud_q3_supplier = '$ud_q3_supplier', ud_q4_productnumber = '$ud_q4_productnumber', ud_q5_quantity = '$ud_q5_quantity', ud_q6_price = '$ud_q6_price', ud_q7_budget = '$ud_q7_budget', ud_q8_link = '$ud_q8_link'
WHERE sid='$sid'";
$result = $conn->query($sql);
if(mysqli_affected_rows()>=1){
echo "<p>($sid) Record Updated<p>";
}else{
echo "<p>($sid) Not Updated<p>";
}
?>
There must be a problem in this last part because I get the (4) Not updated message.
Question 2: Does anyone see the problem here?
I've been trying a few things to tackle the problem but neither are working.
Thank you
mysqli_real_escape method requires the connection to be provided; this was not the case in deprecated mysqli_* methods..
see documentation at http://php.net/manual/en/mysqli.real-escape-string.php
In your case, since you are using object of mysqli:
$conn->real_escape_string($string)
Also for the record, you have a possible inject despite your attempts not to.
You should update $sid = $_POST["sid"]; to $sid = (int) $_POST["sid"]; if it is supposed to be an integer or escape it as well.
With this many variables needing to be escaped though, you should probably look at how to conduct a prepared statement. http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
You use mysqli, not mysql that is good news.
But you continue to use old techniques to pass parameter to query.
So let just try to bind parameters as it should be done with mysqli:
$sql= "UPDATE orders
SET
q1_requested_by = ? ,
q2_productname = ?,
ud_q3_supplier = ?,
ud_q4_productnumber = ?,
ud_q5_quantity = ?,
ud_q6_price = ?,
ud_q7_budget = ?,
ud_q8_link = ?
WHERE sid=? ";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('ssssiddsi', $ud_q1_requested_by, $ud_q2_productname, $ud_q3_supplier, $ud_q4_productnumber, $ud_q5_quantity, $ud_q6_price, $ud_q7_budget, $ud_q8_link, $sid);
$result = $stmt->execute();
if($result && $stmt->affected_rows>0){
echo "<p>($sid) Record Updated<p>";
}else{
echo "Error:\n";
print_r($stmt->error_list);
echo "<p>($sid) Not Updated<p>";
}
I got it to work using the following code:
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php'); }
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sid = (int)$_POST["sid"];
$ud_q1_requested_by = $conn->real_escape_string($_POST["ud_q1_requested_by"]);
$ud_q2_productname = $conn->real_escape_string($_POST["ud_q2_productname"]);
$ud_q3_supplier = $conn->real_escape_string($_POST["ud_q3_supplier"]);
$ud_q4_productnumber = $conn->real_escape_string($_POST["ud_q4_productnumber"]);
$ud_q5_quantity = $conn->real_escape_string($_POST["ud_q5_quantity"]);
$ud_q6_price = $conn->real_escape_string($_POST["ud_q6_price"]);
$ud_q7_budget = $conn->real_escape_string($_POST["ud_q7_budget"]);
$ud_q8_link = $conn->real_escape_string($_POST["ud_q8_link"]);
$sql= "UPDATE orders
SET
q1_requested_by = '$ud_q1_requested_by',
q2_productname = '$ud_q2_productname',
q3_supplier = '$ud_q3_supplier',
q4_productnumber = '$ud_q4_productnumber',
q5_quantity = '$ud_q5_quantity',
q6_price = '$ud_q6_price',
q7_budget = '$ud_q7_budget',
q8_link = '$ud_q8_link'
WHERE sid='$sid'";
$result = $conn->query($sql);
header("Location: edit_orders.php");
?>
which is just simple query, as the original form to enter a new row of data also does. I also decided to remove the error handling at the end since it didn't seem to work with mysqli_affected_rows()>0...
It's probably not a very elegant solution, but it works. Still I'd like to learn more so if anybody would have a useful link explaining php+mysqli basics that would help me much. The links to php.net or mysql.com are for me too brief at this moment though, for me they don't explain what is going on. I'm a total novice to php and mysql and could use some more explanatory/introductary text, maybe with examples, but mostly providing me with an overview of what is going on... Thanks anyway for all the help!

select from mysql table using array

i am trying display a the rows in my database table using the array of ids gotten from another table. i want it to display the first row which is $rowsfriend. and display the second row which is rows .......... but it only displays $rowsfriend
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ochat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM friends where friend1='".($_POST[id])."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rowsfriend = $row["friend2"];
echo $rows;
}
}
$sqll = "SELECT * FROM users WHERE id IN ($rowssfriend)";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0) {
while($roww = $resultt->fetch_assoc()) {
$rowsss = $row["username"];
echo $rowss;
}
}
else {
?>
<h1>Register</h1>
<form action="selectfriends.php" method="post">
id:<br />
<input type="text" name="id" value="" />
<br /><br />
<input type="submit" value="enter" />
</form>
<?php
}
?>
Instead of two queries, you can write this nested query.
$sqll = "SELECT * FROM USERS WHERE ID IN (SELECT friend2 FROM friends WHERE friend1='".$_POST[$id]."')";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0)
{
while($roww = $resultt->fetch_assoc())
{
$rowsss = $row["username"];
echo $rowss;
}
}
Hope this solve your problem .
Please try this version of code instead, if you might:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ochat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT users.* FROM users WHERE users.id IN (SELECT friend2 FROM friends where friend1='".($_POST[id])."')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows = $row["username"];
echo $rows;
}
}
else {
?>
<h1>Register</h1>
<form action="selectfriends.php" method="post">
id:<br />
<input type="text" name="id" value="" />
<br /><br />
<input type="submit" value="enter" />
</form>
<?php
}
?>
As far as I understood the code well, the problem was with the variable name typo as #Admieus wrote but also in the fact that in each iteration of the first loop variable $rowsfriend got overriden with a new value so after the end of the loop, $rowsfriend contained the last id from the result of the first query $sql.
The above version makes only one query using subquery in it to get directly usernames who are friends of friend1 given in $_POST[$id].
I hope it helps.
There are typos in the second loop.
You assign the value to $rowsss and try to echo from $rowss notice the difference.
Also, you assign the fetch_assoc result to $roww and then try to call it again with $row.
$sqll = "SELECT * FROM users WHERE id IN ($rowsfriend)";
$resultt = $conn->query($sqll);
if ($resultt->num_rows > 0) {
while($roww = $resultt->fetch_assoc()) {
$rowsss = $roww["username"];
echo $rowsss;
}
}
Point of improvement is: check your variable names, make names that are easy to understand and hard to mix up.
For instance, the variable containing the sql query should not be named $sql and to make it worse a second query shoul not be named sqll. Instead use names that imply what you are doing.
$querySelectFriendsFrom = "SELECT * FROM users WHERE id IN ($friendId)";
Don't take this as a hard rule, it's more of a tip to prevent silly mistakes.
Update: there was also a type in the query referring to rowssfriend instead of rowsfriend. Fixed above.

Change a variable of a variable

I'm trying to process a large form and hit a bit of a stumbling block. I've tried google for the answer, but I'm not quite sure I'm wording what I need right. My code looks like this.
<?PHP
$exchange = $_POST['exchange'];
$estimate = $_POST['estimate'];
$wp = $_POST['wp'];
$label1 = $_POST['name3'];
$result1 = $_POST['fb1'];
$result2 = $_POST['fb2'];
$username = "-----";
$password = "-----";
$hostname = "-----";
$con = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("-----", $con) or die("Could not select examples");
$query = "UPDATE btsec SET Status='$result1', TM='result2' WHERE Exchange='$exchange' AND Estimate='$estimate' AND WP='$label1' AND SectionID='$label1'";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error($con));
}
}
echo "Sections updated for WP's $wp on $estimate on the $exchange Exchange!";
mysql_close($con);
?>
What I need to do is loop through the query, but each time change the contents of the variable.
$label1 = $_POST['name3']; needs to become $label1 = $_POST['name6'];
$result1 = $_POST['fb1']; needs to become $result1 = $_POST['fb10'];
$result1 = $_POST['fb2']; needs to become $result1 = $_POST['fb11'];
As I say google isn't able to compensate for my bad wording.
The best solution would be to change the form inputs so that they work as arrays:
<input type="text" name="name[3]">
<input type="text" name="name[6]">
<input type="text" name="name[9]">
<input type="text" name="fb[1]">
<input type="text" name="fb[10]">
<input type="text" name="fb[19]">
Then when you submit the form you can iterate over the data:
foreach ($_POST['name'] as $index => $name)
{
}
foreach ($_POST['fb'] as $index => $fb)
{
}
As a side note, you also should look into using prepared statements, or at the very least escaping the data -- you're at risk of SQL injection.

Reading mysql with php and displaying result in dropdown menu

i'm farly new to php and are trying to make a php script where it's suppose to connect to a mysql db and get the vaule id, then show as an option in a drop down menu.
This is the code I have so far (got help from a friend):
$username = "root";
$password = "";
$hostname = "localhost";
$database = "customers";
$id = "";
mysql_connect("$hostname", "$username", "$password") or die (mysql_error()) or die (mysql_error());
mysql_select_db("$database") or die (mysql_error());
$result = mysql_query("SELECT id FROM users WHERE id='$id'") or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$valuestring = $row['id'];
print_r($result);
echo "<option value='$valuestring'>". $valuestring ."</option>";
mysql_close();
}
print_r($id);
But when I use this code the option is returned empty :/
I have also tried to do print_r($result); and that give me Resource id #4, so I guess that works.
If anyone could help me solve this I would be one happy guy :D
the $id value in your code is empty, are you avare of that ?
and can you print the query before sending it to mysql ?
use :
"$query = "select id from table where id = '$id'";
mysql_query($query);
echo $query;
Perhaps if you showed us what output you did get it would help.
the option is returned empty
If the output includes HTML generated inside the loop then that means the query returned at least 1 row. But the only way that echo "<option value='$valuestring'>" would produce an empty string is if $valuestring was an empty string. It's populated from "SELECT id FROM users WHERE id='$id'" implying that you must have a row in your database where id is null or an empty string and $id in your php code is null/empty string - indeed that is the case ($id = "";).
NTW the mysql_close(); should be outside the loop.
Let's simplify this code:
<select name="user" id="user" width="200px" style="width: 200px">
<option value="">Select State</option>
<?php
$query_uf = "SELECT id FROM users WHERE id="'.$id.'";
$result = mysql_query($query_uf,$bd);
while ($users =mysql_fetch_assoc($result)) {
echo "<option value='".$uf['id']."'>".$uf['user']."</option>"; }
?>
</select>
Obs: It's better you use mysqli_query and connect. And, in your code it's missing the connection in mysql_query.
I've previously needed to retrieve a list of albums from a table using a similar method, maybe try this function. Create your form and call the function within the and tags leading this to work. This should list your id(s) where specified in the query.
functions.php (or wherever you'd like to put the function):
function stateList() {
$username = "username";
$password = "password";
$host = "localhost";
$dbname = "dbname";
$id = RETRIEVE VALUE HERE;
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$query = "
SELECT
id,
FROM users
WHERE
id = $id // YOU MAY WANT TO REMOVE WHERE - $ID AS STATED ABOVE, DOESN'T MAKE SENSE.
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$valuestring = $row['id'];
$rows = $stmt->fetchAll();
foreach($rows as $row):
print "<option value='" . $valuestring . "'>" . $valuestring . "</option>";
endforeach;
}
?>
Selection page:
<? include 'functions.php' ?> <!-- This will allow you to call the function. -->
<form action="example.php" method="post" enctype="multipart/form-data">
<select name="album">
<? stateList(); ?> <!-- Calls the function and retrieves all options -->
</select>
<input type="submit" name="submit" value="Submit">
</form>

Categories