Update page not echoing into form

I have an update page where the values are supposed to be “echo” into a form. I am getting no error messages but it is not "echo"ing code below

[php]<?php require_once(‘roster.php’);

$conn=mysqli_connect("$hostname_rostercbc","$database_rostercbc","$password_rostercbc","$username_rostercbc");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

mysql_select_db(“rostercbc”);

$id =$_REQUEST[‘ID’];

$result = mysql_query(“SELECT * FROM players WHERE ID = ‘$id’”);
$test = mysql_fetch_array($result);
if (!$result)
{
die(“Error: Data not found…”);
}
$Name=$test[‘name’] ;
$Number= $test[‘number’] ;
$Position=$test[‘position’] ;
$Team=$test[‘team’] ;

if(isset($_POST[‘save’]))
{
$Name_save = $_POST[‘name’];
$Number_save = $_POST[‘number’];
$Position_save = $_POST[‘postion’];
$Team_save = $_POST[‘team’];

mysql_query("UPDATE players SET name ='$Name_save', number ='$Number_save',
	 position ='$position_save', team ='$Team_save' WHERE ID = '$id'")
			or die(mysql_error()); 
echo "Saved!";

}
?>[/php]

[code]

Untitled Document
Name:
Number
Position
Team
 
[/code]

So new to this so any help would be appreciated.

There are many problems with your script but why would you want to echo out the existing record in the database on the form???

So the end user can make changes to the existing record. So in the demo above the user has already created a kid on a basketball team. Later the end user needs to change the Name, Number, Position, or Team the kid is on. I assumed "echo"ing the selected into a form was the way to do this. Any leads would be helpful. Thanks and if I’m doing everything wrong I’d be more than happy to be pointed in the correct direction.

what is the code in this file roster.php ?

[php]<?php

$hostname_rostercbc = “rostercbc.db.XXXXXXXXX.hostedresource.com”;
$database_rostercbc = “mydatabase”;
$username_rostercbc = “myusername”;
$password_rostercbc = “mypassword”;
$Members = mysql_pconnect($hostname_rostercbc, $username_rostercbc, $password_rostercbc) or trigger_error(mysql_error(),E_USER_ERROR);

?>[/php]

Of course the usernames passwords and data base info is the actual information but I didn’t want it live on a forum.

The reason you are not getting an error is because:

  1. You are loading the HTML version on your browser, where, there is no inclusion of PHP file.
  2. If you load up the PHP version on your browser you will see a lot of errors.
  3. You haven’t included the PHP script into your main file.
  4. You are using the mysqli API to connect to the database but the order of arguments is wrong. The correct order is mysqli_connect (hostname, username, password, database)
  5. If you use mysqli API to connect to the database then you can’t use mysql API to select a database but you have used it in your script.
  6. The $id variable will have no value in it because you are not fetching the ‘ID’ anywhere in your script. Therefore the both the queries you created are invalid.

Here is the updated script that I have re-written for you, hope it will do the job and of course you can study it to find something interesting. ;D

[code]<?php
session_start();
require_once (‘functions.php’);
$conn = db_connect();

    if ($_SERVER['REQUEST_METHOD'] == 'POST' &&
        !empty($_POST['name']) &&
        !empty($_POST['number']) &&
        !empty($_POST['position']) &&
        !empty($_POST['team']) &&
        isset($_POST['recUpdate'])
     ){

      
        $id = $_SESSION['id'];
        $name = $_POST['name'];
        $number = $_POST['number'];
        $position = $_POST['position'];
        $team = $_POST['team'];

        query_rec_eupdate($conn, $id, $name, $number, 
                    $position, $team);

    }

?>

<?php if (isset($_POST['sbtIdModify'])){ echo "Update Record"; } else {
        echo "Modify Record";
     }

?>

<?php if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['idModify']) && isset($_POST['sbtIdModify']) ) { $_SESSION['id'] = $_POST['idModify']; $player = query_form_echo($conn, $_SESSION['id']); ?>
Name:
Number
Position
Team
 
<?php

} else {
?>

ID to be modified:

<?php } mysqli_close($conn); ?> [/code]

[php]<?php

function db_connect(){

/*	Change the DB Connection variables according to your project */

$host = 'localhost';
$user = 'tanzeelniazi';
$pass = 'abc';
$db   = 'phphelp';

$conn = @mysqli_connect($host, $user, $pass, $db);

	if (mysqli_connect_errno()) {

		die("Connection Failed");
	}

return $conn;

}

function query_form_echo($conn, $id){

	$query = "SELECT * FROM players WHERE id = {$id}";
	
	$results = mysqli_query ($conn, $query);

	if (mysqli_affected_rows($conn) == 0) {
	
			 die ("ID doesn't exist");
	}

	if ($results && mysqli_affected_rows($conn) == 1) {
		
		while ($player = mysqli_fetch_assoc($results)){

			$Name 		=	$player['name'] ;
			$Number 	= 	$player['number'] ;
			$Position 	=	$player['position'] ;
			$Team 		=	$player['team'] ;
		}

			$player_info = array(
								  'name' 	 => $Name, 
								  'number' 	 => $Number, 
								  'position' => $Position, 
								  'team' 	 => $Team
								  );

		return $player_info;
	}

}

function query_rec_eupdate($conn, $id, $name, $number, 
							$position, $team){

	$query = "UPDATE players SET
					name = '{$name}',
					number = '{$number}',
					position = '{$position}',
					team = '{$team}'
				
				WHERE 
				id = {$id}
			";
	
	$results = mysqli_query($conn, $query);

	if (!$results){ die ("Can't update the record right now"); }

	return NULL;
}

?>[/php]

Wow you weren’t kidding when you said my code was all wrong…Thank you I will run through the scripts and find better tutorials next time. Any online training programs for php you would recommend?

There are many resources but If you are a newbie then I would recommend Kevin Skoglund’s training on “PHP with MySQL Essential Training”. You can find it on lynda.com, be sure to watch the latest version of the training released in June, 2013.

Ok that script is slick! Need help with just a little modification. I have another page that shows each entry into the database. I’d like to have an Edit button pass the id onto the update page instead of entering it manually. There are to may players to remember their id. So I am starting with this (probably crappy) code.

[code] <?php require_once('roster.php'); ?>

Colorado Basketball Club

All Available Players

<?php $connection = mysql_connect ($hostname_rostercbc, $username_rostercbc, $password_rostercbc) or die('try again in some minutes, please'); mysql_select_db("rostercbc") or die(mysql_error()); $query="SELECT * FROM players";$result=mysql_query($query); $num=mysql_numrows($result);mysql_close(); ?> <?php $i=0;while ($i < $num) {$f1=mysql_result($result,$i,"name"); $f2=mysql_result($result,$i,"number");$f3=mysql_result($result,$i,"position"); $f4=mysql_result($result,$i,"team");$f5=mysql_result($result,$i,"ID");?> <?php $i++;}?>
Name Number Position Team Options
<?php echo $f1; ?> <?php echo $f2; ?> <?php echo $f3; ?> <?php echo $f4; ?> Edit Delete
[/code]

Ok, I will look into it and will reply you back.

Here is your code, I have updated both the previous files so discard them and use the new one :stuck_out_tongue:

functions.php
[php]<?php

function db_connect(){

/*	Change the DB Connection variables according to your project */

$host = 'localhost';
$user = 'tanzeelniazi';
$pass = 'abc';
$db   = 'phphelp';

$conn = @mysqli_connect($host, $user, $pass, $db);

	if (mysqli_connect_errno()) {

		die("Connection Failed");
	}

return $conn;

}

function query_form_echo($conn, $id){

	$query = "SELECT * FROM players WHERE id = {$id}";
	
	$results = mysqli_query ($conn, $query);

	if (mysqli_affected_rows($conn) == 0) {
	
			 die ("ID doesn't exist");
	}

	if ($results && mysqli_affected_rows($conn) == 1) {
		
		while ($player = mysqli_fetch_assoc($results)){

			$Name 		=	$player['name'] ;
			$Number 	= 	$player['number'] ;
			$Position 	=	$player['position'] ;
			$Team 		=	$player['team'] ;
		}

			$player_info = array(
								  'name' 	 => $Name, 
								  'number' 	 => $Number, 
								  'position' => $Position, 
								  'team' 	 => $Team
								  );

		return $player_info;
	}

}

function query_rec_eupdate($conn, $id, $name, $number,
$position, $team){

	$query = "UPDATE players SET
					name = '{$name}',
					number = '{$number}',
					position = '{$position}',
					team = '{$team}'
				
				WHERE 
				id = {$id}
			";
	
	$results = mysqli_query($conn, $query);

	if (!$results){ die ("Can't update the record right now"); }

	return NULL;
}

function query_table_echo($conn){

	$query = "SELECT * FROM players";
	
	$results = mysqli_query ($conn, $query);

	if ($results) {
		
		echo "	<form method=\"post\" action=\"\">
				<table border=\"1px\">
				<tr>
					<th>Name</th>
					<th>Number</th>
					<th>Position</th>
					<th>Team</th>
					<th colspan=\"2\">Options</th>
				</tr>";

		while ($player = mysqli_fetch_assoc($results)){

			$id 		= 	$player['id'];
			$name 		=	$player['name'] ;
			$number 	= 	$player['number'] ;
			$position 	=	$player['position'] ;
			$team 		=	$player['team'] ;

			echo " 
					<tr>
						<td>{$player['name']}</td>
						<td>{$player['number']}</td>
						<td>{$player['position']}</td>
						<td>{$player['team']}</td>
				";

			echo "
					<input type=\"hidden\" name=\"Name[]\"
						value=\"{$name}\">
					<input type=\"hidden\" name=\"ID[]\"
						value=\"{$id}\">
					<input type=\"hidden\" name=\"Team[]\"
						value=\"{$team}\">

					 <td>
						<input type=\"submit\" name=\"{$name}-{$id}\"
						value=\"Edit\">
					 </td>
					 <td>
						<input type=\"submit\" name=\"{$name}-{$id}\"
						value=\"Delete\">
					 </td>

				</tr>
				";
		}

		echo " </table>
			   </form>
			  ";

	}

}

function query_rec_delete($conn, $id, $name){

	$query = "DELETE FROM players 
						WHERE
						id = {$id} AND name = '{$name}'
			";
	
	echo $query;
	$results = mysqli_query($conn, $query);

	if (!$results){ die ("Can't delete the record right now"); }

	return NULL;
}

?>[/php]

record.php
[php] <?php
session_start();
require_once(‘functions.php’);
$conn = db_connect();
?>

Colorado Basketball Club

All Available Players

<?php

	query_table_echo($conn);

	if ($_SERVER['REQUEST_METHOD'] == 'POST'){

		if ($action = array_search('Edit', $_POST)){

			list($_SESSION['name'], $_SESSION['id']) = explode('-', $action);

				$_SESSION['name'] = str_replace("_", " ", $_SESSION['name']);

			header("Location: update.php"); // Your (update.php) HTML code file. Change it if necessary. 

		} elseif ($action = array_search('Delete', $_POST)) {

				list($_SESSION['name'], $_SESSION['id']) = explode('-', $action);

				$_SESSION['name'] = str_replace("_", " ", $_SESSION['name']);

				query_rec_delete($conn, $_SESSION['id'], $_SESSION['name']);

				header("Location: record.php"); // Your (update.php) HTML code file. Change it if necessary. 

		}
		else {

				echo "Wrong Action Selected!";
		}

	}

?>

<?php
mysqli_close($conn);

?>

[/php]

update.php
[php]<?php
session_start();
require_once (‘functions.php’);
$conn = db_connect();

?>

Update Record <?php if (isset($_SESSION['name']) && isset($_SESSION['id']) ){ $id = $_SESSION['id']; $name = $_SESSION['name']; $player = query_form_echo($conn, $_SESSION['id']); ?>
Name:
Number
Position
Team
 
<?php } else {
     header("Location: record.php"); // Redirecting to the Records page if nothing was selected. You can change it if you want.

}

if ($_SERVER[‘REQUEST_METHOD’] == ‘POST’ &&
!empty($_POST[‘name’]) &&
!empty($_POST[‘number’]) &&
!empty($_POST[‘position’]) &&
!empty($_POST[‘team’]) &&
isset($_POST[‘recUpdate’])
) {

     $name       = $_POST['name'];
     $number     = $_POST['number'];
     $position   = $_POST['position'];
     $team       = $_POST['team'];

     query_rec_eupdate($conn, $_SESSION['id'], $name, $number, 
                              $position, $team);

       header("Location: record.php");
     }

?>

<?php mysqli_close($conn); ?> [/php]

Wow! I got it working last night using the GET method but looking through your code I can totally see now how it is supposed to be working. Just looking at some code that has been better written has helped me figure some other things out. I am taking your advice and starting the training this week. I really appreciate your work and your time. I know it is asking alot for you to create code. Cheer’s!

You are welcome and thanks for the appreciation, I’m really glad that my code helped you because I’m not an expert in PHP I’m also a beginner and creating script for you really helped me to learn some new things. Therefore, Thanks to you too. ;D

Sponsor our Newsletter | Privacy Policy | Terms of Service