How to update multiple records in MySQL? - php

I am trying to pull records from a table and update one filed in them. I am able to pull the records and create the form, however the update part is not working.
The code below is above my HTML section.
<?php require_once('../Connections/connect.php'); ?>
<?php
session_start();
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";
// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;
// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they log in.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
}
// Or, you may restrict access to only certain users based on their username.
if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
}
if (($strUsers == "") && true) {
$isValid = true;
}
}
return $isValid;
}
$MM_restrictGoTo = "sorry.php";
if (!((isset($HTTP_SESSION_VARS['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $HTTP_SESSION_VARS['MM_Username'], $HTTP_SESSION_VARS['MM_UserGroup'])))) {
$MM_qsChar = "?";
$MM_referrer = $HTTP_SERVER_VARS['PHP_SELF'];
if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0)
$MM_referrer .= "?" . $QUERY_STRING;
$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
header("Location: ". $MM_restrictGoTo);
exit;
}
?>
<?php
$col_points = "0";
if (isset($HTTP_GET_VARS['tournament_id_num'])) {
$col_points = (get_magic_quotes_gpc()) ? $HTTP_GET_VARS['tournament_id_num'] : addslashes($HTTP_GET_VARS['tournament_id_num']);
}
mysql_select_db($database_camsports, $camsports);
$query_points = sprintf("SELECT cam_registered_tbl.team_id_num, cam_registered_tbl.wins, cam_registered_tbl.losses, cam_registered_tbl.points, cam_teams_tbl.team_name, cam_registered_tbl.registered_id_num FROM cam_registered_tbl, cam_teams_tbl WHERE cam_registered_tbl.tournament_id_num=%s AND cam_teams_tbl.team_id_num=cam_registered_tbl.team_id_num", $col_points);
$points = mysql_query($query_points, $camsports) or die(mysql_error());
$row_points = mysql_fetch_assoc($points);
$totalRows_points = mysql_num_rows($points);
$col_tournament = "0";
if (isset($HTTP_GET_VARS['tournament_id_num'])) {
$col_tournament = (get_magic_quotes_gpc()) ? $HTTP_GET_VARS['tournament_id_num'] : addslashes($HTTP_GET_VARS['tournament_id_num']);
}
mysql_select_db($database_camsports, $camsports);
$query_tournament = sprintf("SELECT cam_tournaments_tbl.tournament_name FROM cam_tournaments_tbl WHERE cam_tournaments_tbl.tournament_id_num=%s", $col_tournament);
$tournament = mysql_query($query_tournament, $camsports) or die(mysql_error());
$row_tournament = mysql_fetch_assoc($tournament);
$totalRows_tournament = mysql_num_rows($tournament);
?>
<?php
//This loops through all the records that have been displayed on the page.
for ($index = 0; $index <= $index_count; $index++) {
/*
This part sets a variable with the names we created in the first section.
We start with 0 and go until the number saved in the $index_count variable.
*/
$varregistered_id_num = 'registered_id_num'.$index;
$varteam_name = 'team_name'.$index;
$varwins = 'wins'.$index;
$varlosses = 'losses'.$index;
$varpoints = 'points'.$index;
/*
This is the variable variable section. We take the value that was assigned
to each name variable. For example the first time through the loop we are
at the record assigned with SubmissionID0. The value given to SubmissionID0
is set from the first section. We access this value by taking the variable
variable of what SubmissionID0 is.
*/
$registered_id_numvalue = $$varregistered_id_num;
$team_namevalue = $$varteam_name;
$winsvalue = $$varwins;
$lossesvalue = $$varlosses;
$pointsvalue = $$varpoints;
//Update the database
$sql = "UPDATE cam_registered_tbl SET points='$pointsvalue',wins='$winsvalue',".
"losses='$lossesvalue' WHERE registered_id_num='$registered_id_numvalue'";
$result = mysql_query($sql);
//If the link was marked approved set the value of the Approved field
if ($goto == '1') {
$insertGoTo = "menu.php";
header(sprintf("Location: %s", $insertGoTo));
}
}
?>
This code is in the body section
<div align="center">
<p><font size="4"><?php echo $row_tournament['tournament_name']; ?></font></p>
</div>
<?php
//Initialize counter variables
$index = 0;
$index_count = 0;
echo "<form method=post action=$PHP_SELF>\n";
echo "<table>\n";
echo "<tr><td><b>Team</b></td>".
"<td><b>Points</b></td></tr>\n";
/*
Assuming we already have retrieved the records from the database into an array setting
$myrow = mysql_fetch_array(). The do...while loop assigns a value to the $xstr variable
by taking the name and concatenating the value of $index to the end starting with 0. So
the first time through the loop $SubmissionIDStr would have a value of SubmissionID0 the
next time through it would be SubmissionID1 and so forth.
*/
do {
$registered_id_numStr = registered_id_num.$index;
$team_nameStr = team_name.$index;
$pointsStr = points.$index;
//This section would print the values onto the screen one record per row
printf("<tr><td><input type=hidden name=%s value=%s>%s</td>
<td><input type=text name=%s value=%s size='5'></td></tr>\n",
$registered_id_numStr, $row_points["registered_id_num"], $row_points["team_name"], $pointsStr, $row_points["points"]);
//Increase counter values by 1 for each loop
$index++;
$index_count++;
} while ($row_points = mysql_fetch_array($points));
// I also had to create an index count to keep track of the total number of rows.
echo "<INPUT TYPE=hidden NAME=counter VALUE=$index_count>\n";
echo "<INPUT TYPE=hidden NAME=goto VALUE='1'>\n";
echo "<INPUT TYPE=submit></form>\n";
echo "</table>";
?>
Any help would be greatly appreciated.

You are doing it right - I don't know of any better approach for your case than running update in for loop. What you should do is to enclose this in a transaction:
mysql_query("start transaction");
for ($index = 0; $index <= $index_count; $index++) {
...
$sql = "UPDATE cam_registered_tbl SET points='$pointsvalue',wins='$winsvalue',"."losses='$lossesvalue' WHERE registered_id_num='$registered_id_numvalue'";
$result = mysql_query($sql);
if (!$result) { // you possibly should do some error checking
mysql_query("rollback"); // cancel the transaction
//print error
exit(0);
}
...
}
mysql_query("commit"); // commit the transaction
If you don't use the transaction, you might end up with just some of the records updated, which will leave the database in inconsistent state. Transaction is very important here - with it, all of the records are updated, or none.
Make sure you use the InnoDB engine, in MyISAM engine the transactions do not work.

I didn't read the whole code, but if you have multiple records and you wish to update the same field (with the same value), you can achieve it like this:
UPDATE mytable SET filed = '$value' WHERE id IN (1,2,3,4,5)
if you have an array with ids, you can do it like this:
$ids = implode(',',$array_ids);
UPDATE mytable SET field = '$value' WHERE id IN ('$ids')
BUT
If the values are different for each id, just run a loop that updates values for each row.

Related

How do i successfully use function array_intersect() here?

I'm trying to make a system where an administrator can add multiple people at the same time into a database. I want this system to prevent the administrator from adding people with email addresses already existing in the database.
IF one of the emails in the _POST["emailaddress"] matches with one of the emailaddresses in the db, the user should get a message saying one of the emails already exists in the database. To achieve this, I've tried using the function array_intersect(). However, upon doing so I get a warning saying:
Warning: array_intersect(): Argument #2 is not an array in ... addingusers.php on line 41
At first i thought it had something to do with the fact my second argument was an associative array, so I tried the function array_intersect_assoc, which returns the same warning. How can I solve this?
The code on addingusers.php
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
//amount of emailaddresses in db
$checkquery2 = mysqli_query($conn, "
SELECT COUNT(emailaddress)
FROM users
");
$result2 = mysqli_fetch_array($checkquery2);
// the previously mentioned amount is used here below
for($i=0; $i<$result2[0]; $i++){
// the actual emails in the db itself
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1;
}
$query1 = $result_array1[$i]["emailaddress"];
}
// HERE LIES THE ISSUE
for($i=0; $i<count($emailaddress); $i++){
if (count(array_intersect_assoc($emailaddress, $query1)) > 0) {
echo "One of the entered emails already exists in the database...";
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}
}
EDIT
as the comments point out, $query1 is indeed not an array it is a string. However, the problem remains even IF i remove the index and "[emailaddress]", as in, the code always opts to the else-statement and never to if.
$query1 is not an array, it's just one email address. You should be pushing onto it in the loop, not overwriting it.
You also have more loops than you need. You don't need to perform SELECT emailaddress FROM users query in a loop, and you don't need to check the intersection in a loop. And since you don't need those loops, you don't need to get the count first.
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','*','*','*');
$condition = false; // this is for the other part of my code which involves inserting the output into db
$name = $_POST["name"];
$affix = $_POST["affix"];
$surname = $_POST["surname"];
$emailaddress = $_POST["emailaddress"];
$password = $_POST["password"];
$q1 = mysqli_query($conn, "
SELECT
emailaddress
FROM
users
");
// goes through all the emails
$result_array1 = array();
while ($row1 = mysqli_fetch_assoc($q1)) {
$result_array1[] = $row1['emailaddress'];
}
$existing_addresses = array_intersect($emailaddress, $result_array1);
if (count($existing_addresses) > 0) {
echo "Some of the entered emails already exists in the database: <br>" . implode(', ', $existing_addresses);
echo '<br><button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script><br>';
$condition = false;
}
else{
$condition = true;
}

PHP - Get the id of the table row clicked

I'm currently creating the account management system of my website and I decided to add a feature that enables me to declare weather a specific account is active or inactive. The data is retrieved from my mysql table.
$query = mysqli_query($DBConnect,"SELECT * from REG");
echo "<table class = 'table' style = 'width:90%;text-align:center'>";
while($getData = mysqli_fetch_assoc($query))
{
$username = $getData['uname'];
$fname = $getData['fname'];
$mname = $getData['mname'];
$lname = $getData['lname'];
$bday = $getData['bday'];
$email = $getData['email'];
$contact = $getData['contact'];
$gender = $getData['gender'];
if($getData['userlevel'] == 1)
{
$userlevel = "user";
}
else
{
$userlevel = "admin";
}
if($getData['status'] == 1)
{
$status = "active";
}
else
{
$status = "disabled";
}
echo "<tr>";
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php' >$status </a></td></tr>";
}
echo "</table>";
This is the content of status.php
session_start();
$DBConnect = mysqli_connect("localhost", "root","","kenginakalbo")
or die ("Unable to connect".mysqli_error());
$query = mysqli_query($DBConnect,"SELECT * from REG where id = '$_SESSION[id]'");
while($getData = mysqli_fetch_assoc($query))
{
$status = $getData['status'];
echo "'$_SESSION[id]'";
}
if($status == 1)
{
$query = mysqli_query($DBConnect, "UPDATE REG SET status = 0 where id = '$_SESSION[id]'");
}
else if ($status == 0)
{
$query = mysqli_query($DBConnect, "UPDATE REG SET status = 1 where id = '$_SESSION[id]'");
}
header("Location: admin/login.php");
What I need to do is get the ID of the row clicked and declare it in my session so that it can be used in the "status.php" file. But in this code, the last id in the table is the one that is declared into the session because of the loop. How do I get the value of the id of the row that is clicked? (is there sort of like onClick function in php? Thank you.
pass id parameter,
status.php?id=$id;
in status.php
$id = $_GET['id'];
Change:
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php' >$status </a></td></tr>";
to:
echo "<td>$username</td><td>$fname</td><td>$mname</td><td>$lname</td><td>$bday</td><td>$email</td><td>$contact</td><td>$gender</td><td>$userlevel</td><td>
<a href ='..\status.php{$getData['id']}' >$status </a></td></tr>";
And in your status.php change $_SESSION['id'] to $_GET['id']. But make sure to first prevent SQL injection either through mysql_real_escape_string($_GET['id']) or through PDO.
There is no onclick function in PHP but you can create a form with a button on each row that holds the value of the row that it is in. Have that form simply do a post or a get request back to the status.php. Adding it to the session might be a bad idea.
Instead of a button you can also create a link modify your loop so that there is a property called $rowid and increment it within your loop.
Perhaps, what you really want is to use a GET superglobal here. You can switch
for
Then, you use $_GET["userid"] instead of $_SESSION[id] on the status.php page.
Also, you dont need a while for the status page. You should check the number of results, if it was 1 it means the user exists, and then you just do a $getData = mysqli_fetch_assoc($query) without the while

How can I insert a value to DB by matching variable in url?

I have a two forms from one form. I can sucessfully store the data to database.when that form submitted user will directed to the second form. I am passing variable $uniqueid in the url from first form to second form. But, when I tried stored the data of the second form into the database that relevant to the same user its not stored.
I want to store mobile number of the user from second page.databse column also mobile number.
This is my code
<?php
include_once 'dbconnect.php';
$a = $_GET['uniquekey'];
if(isset($_POST['btn-signup']))
{
$mobilenumber = $_POST['mobilenumber'];
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if(mysql_num_rows($xxx) > 0) {
$aaa = mysql_query("INSERT INTO who(mobilenumber) VALUES('$mobilenumber')");
}
else{
echo 'wrong';
}
}
?>
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if(mysql_num_rows($xxx) > 0) {
$aaa = mysql_query("UPDATE who setmobilenumber='$mobilenumber' where uniquekey = '$a' ");
}
else{
echo 'wrong';
}
Here you can use update query for update user mobile number.
include_once 'dbconnect.php';
$a = $_GET['uniquekey'];
if(isset($_POST['btn-signup']))
{
$mobilenumber = $_POST['mobilenumber'];
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if($yy>0)
{
$update="update who set mobilenumber=$mobilenumber where uniquekey='$a'";
$query=mysql_query($update);
}
else
{
echo "wrong";
}
}

How do I check if a field in my mySQL database is empty in PHP

I would like to know how to how to check if a field (column) is empty for a specific user.
I have connected successfully to a mySQL database, I have entered a user and I have fields that are empty. I have a post form that allows users to enter information. Based on whether other fields are empty, I would like them to fill accordingly. I would like to use logic to determine whether a field is empty or not. I am using the following:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(trim($_POST['listing_link']) == '') {
}
else if(empty($listing_link1)) {
$listing_link1 = $_POST['listing_link'];
$listing_link1 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link1`='$listing_link1'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link1) && empty($listing_link2)) {
$listing_link2 = $_POST['listing_link'];
$listing_link2 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link2`='$listing_link2'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link2) && empty($listing_link3)) {
$listing_link3 = $_POST['listing_link'];
$listing_link3 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link3`='$listing_link3'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link3) && empty($listing_link4)) {
$listing_link4 = $_POST['listing_link'];
$listing_link4 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link4`='$listing_link4'
WHERE `email`='$emailstring'";
}
else if(!empty($listing_link4) && empty($listing_link5)) {
$listing_link5 = $_POST['listing_link'];
$listing_link5 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link5`='$listing_link5'
WHERE `email`='$emailstring'";
}
$result = mysql_query($query);
}
?>
This code checks whether there is anything entered by the user when they hit the button for the "listing_link". If not, then nothing happens. If something is entered, then it will check to determine if any of the other fields are filled (listing_link1, listing_link2...listing_link5). The $listing_link1 - 5 variables are supposed to take on the information.
I cannot get the other else ifs to run except for:
else if(empty($listing_link1)) {
$listing_link1 = $_POST['listing_link'];
$listing_link1 = mysql_real_escape_string($_POST['listing_link']);
$query = "UPDATE `users`
SET `listing_link1`='$listing_link1'
WHERE `email`='$emailstring'";
And continually running the code by hitting the button for the form just replaces the listing_link1 variable with the newly entered information.
Perhaps there is something wrong with the logic written here. Please help if you can.
You're not defining $listing_link1 until after you've checked to see if it's empty:
else if(empty($listing_link1))
{
$listing_link1 = $_POST['listing_link'];
Flip 'em around:
$listing_link1 = $_POST['listing_link'];
if(empty($listing_link1))
{
If I got you right, this would solve your woes:
$empty = 0;
for($i=1; $i<=5; $i++){
$varname = "listinglink$i";
if(empty($$varname)){
$empty = $i;
break;
}
}
if($empty > 0){
$update_field = "listinglink{$empty}";
$update_data = $_POST['listing_link'];
mysql_query("UPDATE users SET `$update_field`='$update_data'
WHERE email='$emailstring'");
}
What I do there is spin a loop to check which one is the first empty *listing_link* and as soon as I find it, set some variable to its number and quit the loop. From there it's pretty much simple.
What this does: $$varname = 1; is that it takes the value of $varname and tries to use it as a variable name, for example:
$test = "groovy.";
$varname = "test";
echo $$varname; // eqivalent to "echo $test"
Fun technique :)

PHP Function within a function within a loop :S

Firstly, Thaks for taking a look at my question.
I have a function that works perfectly for me, and I want to call another function from within that function however I'm getting all kinds of issues.
Here are the functions then I'll explain what I'm needing and what I'm running into.
They are probably very messy, but I'm learning and thought I'd try get fancy then clean it up.
function GetStation($id){
$x_db_host1="localhost"; // Host name
$x_db_username1="xxxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
// SQL Query Setup for Station Name
$sql="SELECT * FROM stations WHERE ID = $id LIMIT 1";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
$retnm = $rows['CallSign'];
}
mysql_close();
echo $retnm;
} // Closes Function
// List Delegates Function!!!!!!!!!!!!!!!!!!!
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_st_name = GetStation($StatNm);
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}
So I output ListDelegates() in a page and it displays a nice table etc.
Within ListDelegates() i use the GetStation() function.
This is because the table ListDelegates() uses contains the station ID number not name so I want GetStation($id) to output the station name
The problem I'm having is it seems GetStation() is outputting all names in the first call of the function so the first row in the table and is not breaking it down into each row and just one at a time :S
Here's what I think (I'm probably wrong) ListDelegates() is not calling GetStation() for each row it's doing it once even though it's in the loop. ??
I have no idea if this should even work at all... I'm just learning researching then trying things.
Please help me so that I can output station name
At the end of GetStation, you need to change
echo $retnm;
to
return $retnm;
You are printing out the name from inside the function GetStation, when you are intending to store it in a variable. What ends up happening, is that the result of GetStation is effectively echo'ed on the screen outside of any table row. Content that is inside a table but not inside a table cell gets collected to the top of a table in a browser. If you want to see what I mean, just view source from your browser after loading the page.
You don't need to connect to the database in each and every function. Usually you do the database connection at the top of your code and use the handle (in PHP the handle is usually optional) throughout your code. I think your problem is because when you call the function each time it makes a new connection and loses the previous data in the query.
My dear first of all you should place your code of connection with local host and database globally. It should be defined only once. you are defining it in both function.
something like this, and as suggested, you should have connection to database established somewhere else
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
//$d_st_name = GetStation($StatNm);
$sql="SELECT * FROM stations WHERE ID = $StatNm LIMIT 1";
while($rows=mysql_fetch_array($result)){
$d_st_name = $rows['CallSign'];
}
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}

Categories