I'm Unable to set value of textbox using php variable - php

I'm trying to set value of html input type text textboxes to empty when user clicks Search button and empID is not matched, but its giving error:
mysqli_num_rows() expects parameter 1 to be mysqli_result
Here is code:
<html>
<body>
<form action="" method="post">
<h2>Employee Form</h2>
<input type="text" name="empID">
<input type="submit" name="searchRec" value="Search" />
<hr>
Employee ID: <input type="text" name="empIDC" value="<?php echo htmlentities($employeeID); ?>">
<br><br>
Name: <input type="text" name="name" value="<?php echo htmlentities($Name); ?>">
<br><br>
Address: <input type="text" name="address" value="<?php echo htmlentities($Address); ?>">
<br><br>
</form>
<?php
if( isset( $_REQUEST['searchRec'] ))
{
$employeeID = ($_POST["empID"]);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bc140_DB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT empID, Name, Address, Dateofbirth, Salary, Timein from Employee where empID == $employeeID";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result > 0)){ while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) { $employeeID = $row['empID']; $Name = $row['Name']; $Address = $row['Address']; $Dateofbirth = $row['Dateofbirth']; $Salary = $row['Salary']; $timestamp = $row['timeIn']; } }else{ $employeeID = ""; $Name = ""; $Address = ""; $Dateofbirth = ""; $Salary = ""; $timestamp = ""; }
}
?>
</body>
</html>

1st : Change your code order otherwise you will get undefined error . your trying the embed the variable with html before creating the variable .
2nd : should be use single = not == empID = $employeeID
3rd : your mixing mysql with mysqli here mysql_fetch_array($result, MYSQL_ASSOC)
Change to
mysqli_fetch_array($result,MYSQLI_ASSOC);
4th: And also use isset() to confirm that variable exists or not if exists echo it otherwise echo the empty string .
5th: change your if like this if(mysqli_num_rows($result)>0){ }
file.php
<?php
if( isset( $_REQUEST['searchRec'] ))
{
......
$employeeID = $row['empID'];
$Name = $row['Name'];
$Address = $row['Address'];
$Dateofbirth = $row['Dateofbirth'];
$Salary = $row['Salary'];
$timestamp = $row['timeIn'];
......
}
?>
<html>
<body>
.....
Employee ID: <input type="text" name="empIDC" value="<?php if(isset($employeeID)){ echo htmlentities($employeeID); } else { echo ""; } ?>">
.....
</body>
</html>

you have forgotten ';' value="<?php echo htmlentities($employeeID); ?>"

Related

How to pass posted variables to an Anchor ID tag in PHP

I have been trying to insert some data into a table in DB, but the error came at where one of my fields is GET variable from the anchor tag.
To get a clear understanding please take a look at my code:
index page: with a post value of id = 1
<form name="user_form" method="post" action="input.php">
<?php
$sql2 = "SELECT * FROM singleq ";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
$id = $row2['id'];
$cat = $row2['cat'];
?>
<tr >
<input type="hidden" name="q_id" id="q_id" value="<?php echo ($row2["id"]); ?>" />
<input type="hidden" name="tablum" id="tablum" value="singleq" />
<input type="hidden" name="test_id" id="test_id" value="<?php echo $_GET['id'] ?>" />
<td><a href='singleqbanksub.php?id=<?php echo $row2['id'];?>'><?php echo substr(($row2["question"]),0,100) ?>...</a></td>
<td><button class="button button1" type="submit" name="insert-data" id="insert-data" style="width:180px;">Add Question</button></td>
</tr>
<?php }
} else {
echo "";
}
?>
</form>
input.php :
<?php include('db.php'); ?>
<?php
$q_id = $_POST['q_id'];
$test_id = $_POST['test_id'];
$tablum = $_POST['tablum'];
$date = date_default_timezone_set('America/New_York');
$date = date('M-d,Y H:i:s');
$date2 = date('M-d,Y');
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO english (cat, test_id, q_id, tablum)
VALUES ('$cat', '$test_id', '$q_id', '$tablum')";
if ($conn->query($sql) === TRUE) {
header('Location: index.php?id='echo "$test_id";'');
}
else {
echo "ERROR" . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Here as I tried to pass the id through the anchor tag redirection to the same page to loop the process, it shows an error about an unidentified echo.
You are using echo inside header function which is wrong , use like this:
header('Location: index.php?id='.$test_id);

how to use php retrieve data from postgresql and showing in html

I was trying to retrieve data from PostgreSQL database, In PHP.
Retrieving the data is fine but it does not work when it is linked with HTML.
When I click on find button in HTML interface, it did not really retrieve data from PostgrSQL.
Can anybody help?
PHP
$host = "host=sv4gis";
$dbname = "dbname=survey";
$credentials = "user=sde password=dfd54f";
$objectid = "";
$jobno = "";
$unit = "";
$coordinate = "";
$name = "";
$northing = "";
$easting = "";
$elev = "";
$db = pg_connect( "$host $dbname $credentials" );
if(!$db){
echo "Error : Unable to open database\n";
} else {
echo "Opened database successfully\n";
}
function getPosts() {
$posts = array();
$posts[0] = $_POST['objectid'];
$posts[1] = $_POST['jobno'];
$posts[2] = $_POST['unit'];
$posts[3] = $_POST['coordinate'];
$posts[4] = $_POST['name'];
$posts[5] = $_POST['northing'];
$posts[6] = $_POST['easting'];
$posts[7] = $_POST['elev'];
return $posts;
}
// Selection Operation
if (isset($_POST['search'])) {
$data = getPosts();
$sql = "SELECT * FROM monu_from_Lst WHERE OBJECTID = $data[0]";
$ret = pg_query($db, $sql);
if($ret) {
if(pg_num_rows($ret)) {
while($row = pg_fetch_array($ret)) {
echo $objectid = $row['objectid'];
echo $jobno = $row['jobno'];
echo $unit = $row['unit'];
echo $coordinate = $row['coordinate'];
echo $name = $row['name'];
echo $northing = $row['northing'];
echo $easting = $row['easting'];
echo $elev = $row['elev'];
}
echo "Operation done successfully\n";
// pg_close($db);
}else{
echo 'No Data For This Id';
}
} else {
echo 'Result Error';
}
}
HTML
<form action="php_insert_update_delete_search.php" method="post">
<input type="number" name="objectid" placeholder="OBJECTID" value="<?php echo $objectid;?>">
<input type="text" name="jobno" placeholder="JOB#" value="<?php echo $jobno;?>">
<input type="text" name="unit" placeholder="UNIT" value="<?php echo $unit;?>">
<input type="text" name="coordinate" placeholder="COORDINATE" value="<?php echo $coordinate;?>">
<input type="text" name="name" placeholder="NAME" value="<?php echo $name;?>">
<input type="number" name="northing" placeholder="NORTHING" value="<?php echo $northing;?>">
<input type="number" name="northing" placeholder="NORTHING" value="<?php echo $northing;?>">
<input type="number" name="easting" placeholder="EASTING" value="<?php echo $easting;?>">
<input type="number" name="elev" placeholder="ElEVATION" value="<?php echo $elev;?>">
<div>
<input type="submit" name="search" value="Find">
</div>
</form>
Your code seems to be fine. The problem might be with
<form action="php_insert_update_delete_search.php" method="post">
If you are posting the file to itself try using
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
Make sure your query runs successfully. if your query does not run successfully
try following
$sql = "SELECT * FROM \"monu_from_Lst\" WHERE objectid= $data[0]";
I have working code as following
<?php
$host = "host=localhost"; // use your hostname
$dbname = "dbname=blogsitedb"; // use your dbname
$credentials = "user=postgres password=admin"; // use your credentials
$objectid = "";
$jobno = "";
$unit = "";
$coordinate = "";
$name = "";
$northing = "";
$easting = "";
$elev = "";
$db = pg_connect("$host $dbname $credentials");
if(!$db)
{
echo "Error : Unable to open database\n";
}
else
{
echo "Opened database successfully\n";
}
function getPosts()
{
$posts = array();
$posts[0] = $_POST['objectid'];
$posts[1] = $_POST['jobno'];
$posts[2] = $_POST['unit'];
/*
$posts[3] = $_POST['coordinate'];
$posts[4] = $_POST['name'];
$posts[5] = $_POST['northing'];
$posts[6] = $_POST['easting'];
$posts[7] = $_POST['elev'];
*/
return $posts;
}
// Selection Operation
if(isset($_POST['search']))
{
$data = getPosts();
$sql = "SELECT * FROM \"monu_from_Lst\" WHERE objectid= $data[0]";
$ret = pg_query($db, $sql);
if($ret)
{
if(pg_num_rows($ret))
{
while($row = pg_fetch_array($ret))
{
echo $objectid = $row['objectid'];
echo $jobno = $row['jobno'];
echo $unit = $row['unit'];
/*echo $coordinate = $row['coordinate'];
echo $name = $row['name'];
echo $northing = $row['northing'];
echo $easting = $row['easting'];
echo $elev = $row['elev'];*/
}
echo "Operation done successfully\n";
// pg_close($db);
}
else
{
echo 'No Data For This Id';
}
}
else
{
echo 'Result Error';
}
}
?>
<!DOCTYPE Html>
<html>
<head>
<title>PHP INSERT UPDATE DELETE SEARCH</title>
</head>
<body>
<form action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<input type="number" name="objectid" placeholder="OBJECTID" value="<?php echo $objectid;?>"><br><br>
<input type="text" name="jobno" placeholder="JOB#" value="<?php echo $jobno;?>"><br><br>
<input type="text" name="unit" placeholder="UNIT" value="<?php echo $unit;?>"><br><br>
<input type="text" name="coordinate" placeholder="COORDINATE" value="<?php echo $coordinate;?>"><br><br>
<input type="text" name="name" placeholder="NAME" value="<?php echo $name;?>"><br><br>
<input type="number" name="northing" placeholder="NORTHING" value="<?php echo $northing;?>"><br><br>
<input type="number" name="northing" placeholder="NORTHING" value="<?php echo $northing;?>"><br><br>
<input type="number" name="easting" placeholder="EASTING" value="<?php echo $easting;?>"><br><br>
<input type="number" name="elev" placeholder="ElEVATION" value="<?php echo $elev;?>"><br><br>
<div>
<!-- Input For Find Values With The given objectid -->
<input type="submit" name="search" value="Find">
</div>
</form>
</body>
</html>

How to stop resubmission of a form using Php?

I am making a web-application for Quiz competition. For the purpose, I wrote a php script which is processed by the same page. Now when I am adding scores and question numbers, the score is incremented or remain unchanged depending upon the previous answer if someone is refreshing the page. Now I googled the problem and found something like PRG.But this method works if the page is processed by other page (What I think ). Again, a friend of mine told me to use Javascript. But what if someone has turned Js off? Can't we have a solution in php itself. I tried session method also, but I did not fix the issue .
Please help me .
PHP Quiz script is here:
<?php
// starting session
session_start();
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// $query = ;
//this get is taking level from index.php
if ( isset($_GET['level']))
{
$level = $_GET['level'];
}
else
{
$level = 'E';
}
//connecting to Data Base
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit']))
{
$level = $_POST['level'];
// $_SESSION['flag']
$answer = $_POST['answer'];
if ( !empty($answer))
{
$qid = $_POST['qid'];
$select = $_POST['select'];
$user_id = $_SESSION['user_id'];
$result = mysqli_query($dbc,"select * from question where qid = '$qid'")
or die("Error in connection.");
$row = mysqli_fetch_array($result);
if ( $row['ANSWER'] == $answer)
{
echo 'Your answer is correct.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',1)")
or die ("Error in updating values in user_question");
}
else
{
echo 'Your answer is incorrect.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',0)")
or die ("Error in updating values in user_question");
}
$answer = "";
}
else
{
echo 'You did not answer the previous question';
}
}
$user_id = $_SESSION['user_id'];
// $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//Taking a random value from the list of question
$id_list = array();
// echo $user_id;
// echo $level;
$result = mysqli_query($dbc,"select * from question where lvl = '$level' and user_id != '$user_id' and qid not in ( select qid from user_question where user_id = '$user_id' )");
while ( ($row = mysqli_fetch_array($result)) )
{
if ( $row['user_id'] != $user_id)
array_push($id_list,$row['qid']);
}
// print_r($id_list);
//Whether user viewed all the questions
if ( empty($id_list))
{
echo 'Great, You have visited all the question, wait for more update ';
echo '<br>';
echo '❤ View Your Score<br />';
exit();
}
// Taking a random value after shuffling it
shuffle($id_list);
$select = $id_list[array_rand($id_list)];
$result = mysqli_query($dbc,"select * from question where qid='$select'");
// Showing the question
while ( ($row = mysqli_fetch_array($result)) )
{
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h3> <?php echo $row['sawal']; ?></h3>
<form method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="radio" name=" answer" value="A" ><?php echo $row['a']; ?><br>
<input type="radio" name=" answer" value="B" ><?php echo $row['b']; ?><br>
<input type="radio" name=" answer" value="C" ><?php echo $row['c']; ?><br>
<input type="radio" name=" answer" value="D" ><?php echo $row['d']; ?><br>
<input type="hidden" name = "qid" value="<?php echo $row['qid'] ?>">
<!-- <input type="hidden" name = "range" value="<?php $range ?>"> -->
<input type="hidden" name = "level" value="<?php echo $level ?>">
<input type="hidden" name = "select" value="<?php echo $select ?>">
<input type="submit" name="submit" value="ANSWER"/>
</form>
</body>
</html>
<?php
require_once('view_score.php');
}
?>
Edit:
I changed my code as Mat is suggested. But it is not allowing me to have different question from the table?
The revised php code is here:
<?php
// starting session
session_start();
if (!isset($_SESSION['user_id'])) {
echo '<p class="login">Please log in to access this page.</p>';
exit();
}
else {
echo('<p class="login">You are logged in as ' . $_SESSION['username'] . '. Log out.</p>');
}
// $query = ;
//this get is taking level from index.php
if ( isset($_GET['level']))
{
$level = $_GET['level'];
}
else
{
$level = 'E';
}
//connecting to Data Base
require_once('connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (isset($_POST['submit']))
{
$is_new_post = true;
if (isset($_SESSION["myform_key"]) && isset($_POST["myform_key"]))
{
if($_POST["myform_key"] == $_SESSION["myform_key"] ){
$is_new_post = false;
}
}
if($is_new_post){
$_SESSION["myform_key"] = $_POST["myform_key"];
$level = $_POST['level'];
// $_SESSION['flag']
$answer = $_POST['answer'];
if ( !empty($answer))
{
$qid = $_POST['qid'];
$select = $_POST['select'];
$user_id = $_SESSION['user_id'];
$result = mysqli_query($dbc,"select * from question where qid = '$qid'")
or die("Error in connection.");
$row = mysqli_fetch_array($result);
if ( $row['ANSWER'] == $answer)
{
echo 'Your answer is correct.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',1)")
or die ("Error in updating values in user_question");
}
else
{
echo 'Your answer is incorrect.';
mysqli_query($dbc,"insert into user_question ( qid,user_id,answer_key) values ( '$select','$user_id',0)")
or die ("Error in updating values in user_question");
}
$answer = "";
}
else
{
echo 'You did not answer the previous question';
}
}
}
$user_id = $_SESSION['user_id'];
// $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
//Taking a random value from the list of question
$id_list = array();
// echo $user_id;
// echo $level;
$result = mysqli_query($dbc,"select * from question where lvl = '$level' and user_id != '$user_id' and qid not in ( select qid from user_question where user_id = '$user_id' )");
while ( ($row = mysqli_fetch_array($result)) )
{
if ( $row['user_id'] != $user_id)
array_push($id_list,$row['qid']);
}
// print_r($id_list);
//Whether user viewed all the questions
if ( empty($id_list))
{
echo 'Great, You have visited all the question, wait for more update ';
echo '<br>';
echo '❤ View Your Score<br />';
exit();
}
// Taking a random value after shuffling it
shuffle($id_list);
$select = $id_list[array_rand($id_list)];
$result = mysqli_query($dbc,"select * from question where qid='$select'");
// Showing the question
while ( ($row = mysqli_fetch_array($result)) )
{
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h3> <?php echo $row['sawal']; ?></h3>
<form method = "POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="radio" name=" answer" value="A" ><?php echo $row['a']; ?><br>
<input type="radio" name=" answer" value="B" ><?php echo $row['b']; ?><br>
<input type="radio" name=" answer" value="C" ><?php echo $row['c']; ?><br>
<input type="radio" name=" answer" value="D" ><?php echo $row['d']; ?><br>
<input type="hidden" name = "qid" value="<?php echo $row['qid'] ?>">
<!-- <input type="hidden" name = "range" value="<?php $range ?>"> -->
<input type="hidden" name = "level" value="<?php echo $level ?>">
<input type="hidden" name = "select" value="<?php echo $select ?>">
<input type="hidden" name="myform_key" value="<?php echo md5("CrazyFrogBros"); ?>" />
<input type="submit" name="submit" value="ANSWER"/>
</form>
</body>
</html>
<?php
require_once('view_score.php');
}
?>
I tried session method also, but I did not fix the issue
I don't know how you code it but you can try this:
1. Set a session token with unique hash value e.g.
$_SESSION['formtoken'] = sha1(uniqid('', true));
include it in your form (input hidden) value = $_SESSION['formtoken']
everytime the user submit the form reset the $_SESSION['formtoken'] value

editing and deleting records in a database using radio buttons

<?php
$user_name = "root";
$password = "";
$database = "my_db";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if(isset ($_POST['name']))
{
$name = $_POST['name'];
if(mysql_query("INSERT INTO persons VALUES(' ' , '$name') "))
echo "Successful Insertion!";
else
echo "Please try again!";
}
$result = mysql_query("SELECT * FROM persons");
?>
<html>
<head>
<style type = "text/css">
li { list-style-type: none; display: inline; padding: 10px; text-align: center;}
</style>
</head>
<body>
<form action = " . " method = "POST">
Name: <input type = "text" name = "name"><br>
<input type = "submit" value = "Enter">
</form>
<form name = "delete_form" method = "POST" action = "delete.php" >
<input type = "submit" name = "deleteRecord" value = "Delete Record" />
</form>
<h1>List of Names</h1>
<table border = "1" width = "100%" cellpadding = "5" cellspacing = "2">
<tr>
<td><strong></strong></td>
<td><strong>ID</strong></td>
<td><strong>Company</strong></td>
<td><strong>Edit</strong></td>
<td><strong>Delete</strong></td>
</tr>
<?php while ($row = mysql_fetch_array($result)) { ?>
<tr>
<td><input type="radio" Name="id" value="<?php echo $row['id']; ?>" ></td>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo "<a href = 'edit.php?id=$row[id]'>edit</a>" ?></td>
<td><?php echo "<a href = 'delete.php?id=$row[id]'>delete</a>" ?></td>
</tr>
<?php } ?>
<form name = "edit_form" method = "POST" action = " edit.php?edit= "<?php echo $row['id'] ?> >
<input type = "submit" name = "editRecord" value = "Edit Record" />
</form>
</table>
<?php
while($row = mysql_fetch_array($result))
echo "<li>$row[id]</li> . <li>$row[name]</li> <li> <a href = 'edit.php?edit=$row[id]'>edit</a> </li> <li> <a href = 'delete.php?del=$row[id]'>delete</a></li> <br>";
?>
</body>
</html>
edit.php
<?php
$user_name = "root";
$password = "";
$database = "my_db";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
$row = " ";
if (isset($_POST['id']))
{
// if there is an id sent through POST and it isn't null/empty, use that
$id = $_POST['id'];
$SQL = "SELECT * FROM persons WHERE id = '$id' ";
$result = mysql_query($SQL);
$row = mysql_fetch_array($result);
}
else
{
// otherwise use id sent through GET links
$id = $_GET['id'];
$SQL = "SELECT * FROM persons WHERE id = '$id' ";
$result = mysql_query($SQL);
$row = mysql_fetch_array($result);
}
if(isset($_POST['newName']))
{
$id = $_POST['id'];
$newName = $_POST['newName'];
$SQL = "UPDATE persons SET name = '$newName' WHERE id = '$id' ";
$result = mysql_query($SQL) or die("Could not update database" . mysql_error());
echo "<meta http-equiv = 'refresh' content = '0 ; url = index.php'>";
}
?>
<form action = " edit.php" method = "POST">
ID: <input type = "text" name = "id" value = "<?php echo $row[0] ?>"<br><br>
Name: <input type = "text" name = "newName" value = "<?php echo $row[1] ?>"<br><br>
<input type = "submit" value = "Update">
</form>
Hello,
The code above shows how to edit and delete records in a database. Originally, the edit and delete options were in the form of links to a php script which performed the required action. The ID number of the selected row gets passed to the edit or delete php file which then does the action that the user selects (refer to the comments in the code above) I am now trying to modify this code so that I can use a radio button to select a record and then edit or delete the record using radio buttons. I know this sounds trivial but I am having some difficulty with it. Any assistance would be greatly appreciated. Thank you.
Hello Tom. I have made the changes that you suggested but I it still giving the same problem. I have included the edit.php file in case you want to have a look.
The value of your radio buttons needs to contain the ID of the record to be edited.
<td><INPUT TYPE="Radio" Name="radio" value="<?php echo $row['id']; ?>"></td>
Then when you submit the form, you will know the record you are editing has id of value $_POST['radio'].
Though you are already using GET method to pass IDs (through your edit and delete links). I would recommend having consistency, and passing all IDs with parameter id. So
Use this
<td><?php echo "<a href = 'edit.php?id=$row[id]'>edit</a>"; ?></td>
<td><?php echo "<a href = 'delete.php?id=$row[id]'>delete</a>"; ?></td>
And this
<td><input type="radio" name="id" value="<?php echo $row[id]; ?>"></td>
Then in edit.php and delete.php, check to see if an ID was passed through POST (if someone submitted the form) or through GET (they clicked a link), then use whichever has a value.
<?php
if (!empty($_POST['id']))
{
// if there is an id sent through POST and it isn't null/empty, use that
$id = $_POST['id'];
}
else
{
// otherwise use id sent through GET
$id = $_GET['id'];
}
I should also mention that mysql_fetch_array is deprecated and you should be using PDO or MySQLi. Read more here: http://www.php.net/mysql_fetch_array

previous/next record button php/mysql woes

My question deals with my next/previous buttons. I can get my update/delete buttons to work, but I'm so ready to tear out my hair when dealing with the next/previous buttons. Any help would be spectacular! Here's my code. Also, I'm pretty new to PHP so if this is bad coding, please let me know and point me in the right direction so I can fix my mistakes. Thanks!!!
session_start();
include "connectionfile.php";
if (isset($_POST['fname']) &&
isset($_POST['lname']) &&
isset($_POST['email']) &&
isset($_POST['login']) &&
isset($_POST['password']) &&
isset($_POST['super']) &&
isset($_POST['foldername']))
{
$id = get_post('id');
$fname = get_post('fname');
$lname = get_post('lname');
$email = get_post('email');
$login = get_post('login');
$password = hash('sha256', get_post('password'));
$super = get_post('super');
$foldername = get_post('foldername');
if ($_POST['submit']==0){
$query = mysql_query("SELECT * FROM `Logins` WHERE ID < '".$id."' ORDER BY ID DESC LIMIT 1;");
while($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['fname'];
$lname = $row['lname'];
$email = $row['email'];
$login = $row['login'];
$password = $row['password'];
$super = $row['super'];
$foldername = $row['foldername'];
}
}else if ($_POST['submit']==1){
$query = "UPDATE Logins SET fname = '$fname', lname='$lname', email='$email".'#carouselclinical.com'."', login='$login', password='$password', super='$super', foldername='$foldername'";
$query .= "WHERE ID = '$id';";
if (!mysql_query($query, $connect))
echo "INSERT failed: $query<br />" .
mysql_error() . "<br /><br />";
}else if($_POST['submit']==2){
$delete_query = "DELETE FROM Logins WHERE ID = '".$id."';";
mysql_query($delete_query);
$rc = mysql_affected_rows();
echo "Rows Affected " . $rc;
}
if ($_POST['submit']==3){
$query = mysql_query("SELECT * FROM `Logins` WHERE ID= '". $id ."' ORDER BY ID ASC LIMIT 1;");
while($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['fname'];
$lname = $row['lname'];
$email = $row['email'];
$login = $row['login'];
$password = $row['password'];
$super = $row['super'];
$foldername = $row['foldername'];
}
}
}
mysql_close($connect);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
<form action="" method="post"><pre>
id <input type="text" readonly="readonly" name="id" value="<?php echo "$id"; ?>" />
First Name <input type="text" name="fname" value="<?php echo "$fname"; ?>" />
Last Name <input type="text" name="lname" value="<?php echo "$lname"; ?>" />
Email <input type="text" name="email" value="<?php echo "$email"; ?>" /> There's no need to put #carouselclinical.com.
Login <input type="text" name="login" value="<?php echo "$login"; ?>"/>
Password <input type="text" name="password" value="<?php echo "$password"; ?>"/>
Super? <input type="text" name="super" value="<?php echo "$super"; ?>" />
foldername <input type="text" name="foldername" value="<?php echo "$foldername"; ?>" />
<button name="submit" value="0">Previous</button>
<button name="submit" value="1">UPDATE</button>
<button name="submit" value="2">Delete</button>
<button name="submit" value="3">Next</button>
</pre>
Home <br />
Log out
</form>
Try adding an else right above mysql_close($connect);. My guess is that on the initial page load you are not posting any values, so no action is taken. This will create a default ID if none is defined in your top if.
else{
$query = mysql_query("SELECT * FROM `Logins` ORDER BY ID ASC LIMIT 1;");
while($row = mysql_fetch_array($query)){
$id = $row['ID'];
$fname = $row['fname'];
$lname = $row['lname'];
$email = $row['email'];
$login = $row['login'];
$password = $row['password'];
$super = $row['super'];
$foldername = $row['foldername'];
}
Also, on your if ($_POST['submit']==3), you need to change the = to > in your $query so you can get the next record. Currently you would be selecting the same ID, not the next higher.
$query = mysql_query("SELECT * FROM `Logins` WHERE ID > '". $id ."' ORDER BY ID ASC LIMIT 1;");
Finally, when doing Previous/Next you also need to take into consideration how you will deal with Previous when you are on the first ID, and Next when you are on the last id, as you will return an empty result set from MySQL.

Categories