I'm new to php.
I have this page:
<?php
function renderForm($id, $StaffFullName, $StaffJobPosition, $error)
{
?>
<!doctype html>
<html>
<head><title></title></head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div>'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<p>ID: <?php echo $id; ?></p>
Name: * <input type="text" name="StaffFullName" value="<?php echo $StaffFullName; ?>"/><br/>
Job Position: * <select name="JobPosition">
<?php
$query = "SELECT * FROM LUT_JOBPOS";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
if ($StaffJobPosition == $row['JobposID'])
{
echo "<option value='{$row['JobposID']}' selected='selected'>{$row['JobposTitle']}</option>";
}
else {
echo "<option value='{$row['JobposID']}'>{$row['JobposTitle']}</option>";
}
}
$result->close();
?>
</select><br/>
<input type="submit" name="submit" value="Update">
<input type="button" onClick="parent.location='view.php'" value="Back">
</div>
</form>
</body>
</html>
<?php
}
// connect to the database
require_once('../../authenticate.php');
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// do some funky stuff
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checking that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$query = "SELECT * FROM STAFF WHERE StaffID=$id";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$result->close();
// check that the 'id' matches up with a row in the database
if($row)
{
// get data
$StaffFullName = $row['StaffFullName'];
$StaffJobPosition = $row['StaffJobPosition'];
// show form
renderForm($id, $StaffFullName, $StaffJobPosition, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
}
?>
So, what happens here is this:
When you open the page like edit.php?id=1, it fetches the data of the associated record from STAFF table and shows them on page for the user to edit them.
This part of the code works fine.
I also want the user to be able to select "Job Position" possible values from a drop down box. The drop down box should get its data from another table in database, LUT_JOBPOS.
This is the part of the code that doesn't work.
I was using mysql_query commands before on this page and it worked perfectly. However I was told to switch on mysqli_query instead.
Since I did the conversion I can't find how to run these two queries on the same script.
I messed a little bit with the require_once command and depending on where I call it I can run one query or another, but never both of them.
Looking at the logs of my web host the only thing I can see that may be relevant to my issue is:
"mod_fcgid: stderr: PHP Notice: Undefined variable: connection in /var/www/vhosts/myhostdomain.com/httpdocs/prod15/admin/staff/edit.php on line 24"
The connection variable comes from authenticate.php and it holds the connection parameters to the database. I'm sure it's set otherwise the first query (that gets the user data) wouldn't work.
I read somewhere that you can't run two sqli queries on the same script.
Then how I'm supposed to use a LUT table (lookup table)?
PS: I know that for showing the data I can use a UNION and that's what I do.
But when I edit the data I want the user to be able to select only from the possible values that exist on the LUT table (drop down select box)
Any help?
You have a lot of issues in your code. You really need to review it before use it in some real application, but for your specific problem, here is my guess.
You are calling the line $result = mysqli_query($connection, $query); in the line 24 and only after taht you call require_once('../../authenticate.php');.
As you said, the $connection var is defined in the authenticate.php, so in the line 24 is undefined.
Try to use require in the first line of your php script.
Related
I have been looking for 3 weeks on the Internet for an answer to this question and cannot find anything that even comes close or in handy. I have a Database Table that i need to have checked. If a Users_ID is present in that table, I would like my code to display an update.php link in my form action="" tag and if the Users_ID is not present in that db table, then i would like to have an Insertdb.php page to be linked in the form instead of an update.php page. Here is what I have:
PHP Code:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
while($display = $results->fetch_array(MYSQLI_ASSOC)) {
$uid = $display['uid'];
if($display['uid']==""){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
And my HTML section looks like this:
HTML Code:
<form action="<?php echo $pagelink; ?>" method="POST">
<input type="text" value="" placeholder="Insert Value" name="something" />
<input type="submit" value="Submit Data" name="submit_data_to_db" />
</form>
How would I go about doing this? My current method Posted above is what I'm currently using, however its displaying only <form action="" method="POST"> when i check it against the pages view-source. Please help me anyway you can. Any and all help would be greatly appreciated. Thank you
you usually use num_rows method:
<?php
session_start();
error_reporting(E_ALL);
include_once("dbconnect.php");
$users_id = $_SESSION['user_id'];
$sql = "SELECT * FROM dbtable WHERE uid=$users_id";
if($results = $con->query($sql)) {
if($results->num_rows() > 0){
$pagelink = "insertintodb.php";
}else{
$pagelink = "updatedb.php";
}
}
$results->close();
}
?>
I see you use $con but I see nowhere you have declared it.
Can you confirm that actually exists? It is possible your script is halting its execution at that point.
Also a few things I would implement in there:
1. When you use variables that come from external sources (like your forms), or even other variables really, always care for SQL injection;
2. Your if & else can be reduced to just an if (when you find an ID). To all others case, you wish a default behaviour that is your else. So something like this:
$pageLink = "insertintodb.php";
if (!empty($display['uid'])) {
$pageLink = "updatedb.php"
}
I have a div statement with two nested divs inside. The first nested div is a form that contains a drop down menu that allows the person to select a basic school subject:
<form id="request" action="<?php echo $_SERVER['PHP_SELF']?> method="post">
<div id='d2'>
<p id='p2'>Subject:
<select id="s" name="subject">
<option value="English">English</option>
<option value="Social Studies">Social Studies</option>
<option value="Math">Math</option>
<option value="Science">Science</option>
</select>
</p>
<input type="button" value="Find"/>
</div>
</form>
The second nested div will print out, using PHP, a previously initialized array of tutors that can help the student user, along with a link allowing the person to choose a specific tutor. Please forgive me for the less-than-stellar formatting, I'm still a beginner:
<div id='div3'>
for ($i=0; $i<count($tutors); $i++)
{
echo "<div>'".$tutors[$i]."'</div><br/>"
. 'Choose me' . "<br/>";
}
</div>
The array is initialized at the very beginning of the php class by connecting to MySQL and then pulling out tutors from the database that are tutor users and tutor in the subject the student user has selected. Again, please forgive me for any bugs, I'm still learning:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
$sub = $_POST['subject'];
$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$msg = "";
if (mysqli_connect_errno())
{
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = tutor AND Subject ='".$sub."'");
$tutors = array();
while ($row = mysqli_fetch_assoc($query))
{
$tutors[] = $row["Username"];
}
}
else
{
echo "Failed form.";
}
?>
The problem pressing me the most right now is that failed form is always shown on the screen. I suspect this is because the form has been nested inside a div. Is there any way around this? Or is it a different problem(s)?
I'm also wondering if the code will indeed show what I want in the second nested div, or if there are bugs in that too (I'll style it later).
I am basing my solution. on the following assumption. According too these lines from your post. The second nested div will print out, using PHP, a previously initialized array of tutors that can help the student user, along with a link allowing the person to choose a specific tutor. Please forgive me for the less-than-stellar formatting, I'm still a beginner:>>>>>> those line were from your post.
Please read the comment in the code carefull. There i explain what i change and suggestions.
This the code
<!--
<form id="request" action="<?php //echo $_SERVER['PHP_SELF']?> method="post">-->
/*
* The line above is wrong and as you may understand by the comments of other user,
you dont need to give anything in the action as you are posting it on the same
* page. so you can delete it. and add this line below one.
*/
<form action="" method="post">
<div id='d2'>
<p id='p2'>Subject:
<select id="s" name="subject">
<option value="English">English</option>
<option value="Social Studies">Social Studies</option>
<option value="Math">Math</option>
<option value="Science">Science</option>
</select>
</p>
<!--<input type="button" value="Find"/>--->
<input type="submit" value="Find"/>
</div>
</form>
<div id='div3'>
<?php
//I am leaving these php tag for the reference only that you used it in your original code.
//You dont need those lines
?>
</div>
<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
$sub = $_POST['subject'];
//$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$con = mysqli_connect("127.0.0.1", "root", "", "mydb");
$msg = "";
if (mysqli_connect_errno())
{
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = 'tutor' AND Subject ='".$sub."'")or die(mysqli_error($con));
// $tutors = array(); You dont need that line either.
while ($row = mysqli_fetch_assoc($query))
{
$tutors = $row["username"];
echo "<div>'".$tutors."'</div><br/>"
. 'Choose me' . "<br/>";
/*
* **Here is the suggestion**. The link you are giving to
* the user is always going to be SelectedTutor.php.
* I dont think this what you want. you may want to
* show tutor profile or wanna do some thing else when
* somebody click on the link. Lets say you want show
* the tutor profile. Than you have to run another query.
* and should be able to generate link accordingly.
* I am giving you hint how you can do it in case you want to do it.
*/
/*
* you should change that line to this line link one to this
* echo "<div>'".$tutors."'</div><br/>"
* . 'Choose me' . "<br/>";
* If you notcie i added this parth after SelectedTutor.php, this one ?tutor='.$tutors.'
* Than your url will be different when ever user click on the link.
* Hope i did not confused you
*/
}
}
else
{
echo "Failed form.";
}
?>
And you ask why you are getting message of Failed form. In short why your else statement is running. to understand see the expanation below.
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//I removed the code just left the basic shell so you can understand
}
else
{
echo "Failed form.";
}
If you read the above code you will understand why you are getting Failed form message each time when you run the code. You will not get this message when you click on submit.
Reason: Reason is this, in those lines your saying that if Request method is post, than run this bit of code. and Else echo this message out. means whenever your request method is not post run this else statement.
but the thing is that you only sending post request after clicking on the button. before that, there is no post request. so thats why you are getting this message each time you run your script and than it disappear when you click on submit. cause you send the post request.
English is not the first language if i confused you let me know i will explain it again.
Although you have asked for help with PHP/HTML, this is really a job for jQuery/AJAX. Don't worry, though -- it's much simpler than you might think.
The advantage to using AJAX is that you stay on the same page, and the page does not refresh -- but the dropdown selection is sent to a PHP file (that you specify), the MySQL database is consulted, and a response (in HTML) is returned.
Inside the AJAX success function, (did you hear that? Inside the success function!) you receive the HTML returned by the other PHP file and you then plunk the returned HTML into an existing DIV.
Here are some simple examples:
AJAX request callback using jQuery
(1) You would not need to put DIV d2 into <form> tags. Not necessary with AJAX
(2) Your jQuery code would look like this:
<script type="text/javascript">
$('#s').change(function(){
var sub = $(this).val();
$.ajax({
type: 'post',
url: 'my_php_file.php',
data: 'subj=' +sub,
success: function(resp){
$('#div3').html(resp);
}
});
});
</script>
The above script can be placed anywhere in the document, or in the head tags, or included in a separate document.
(3) You must reference the jQuery library, as per the first example in the "AJAX request callback..." link.
(4) There will be no need for the Find button, because the code will fire as soon as the dropdown value is changed. It takes microseconds to communicate with the server and stick the list of tutors in the div3 div.
(5) The div3 div must already exist on the page (but it can be empty).
(6) The PHP file (called my_php_file.php in the code above) would be exactly as you wrote, except that it would create an output variable containing the HTML to be plunked into the div3 div. For example:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
$sub = $_POST['subj'];
$con = mysqli_connect("127.0.0.1", "root", "//removed", "mydb");
$msg = "";
if (mysqli_connect_errno()){
$msg = "Failed to connect to MySQL: " . mysqli_connect_error();
echo $msg;
}
$query = mysqli_query($con, "SELECT * FROM User WHERE Role = tutor AND Subject ='".$sub."'");
$tutors = array();
while ($row = mysqli_fetch_assoc($query)) {
$tutors[] = $row["Username"];
}
$out = '';
for ($i=0; $i<count($tutors); $i++) {
$out .= '<div>' .$tutors[$i]. '</div><br/>
Choose me<br/>
';
}
}else{
$out = "Failed form.";
}
echo $out;
?>
All above code is untested, but could work...
I'm trying to get a row from the DB using php, i've made an html form that's supposed to take a book title from users and gets the review from the DB about this book, and then post it in an input text, the form's action leads to the following function :
function GetReview($BookTitle)
{
require'DB.php';
if(empty($_POST['BookTitle']))
{
echo " You must enter a book name!";
return false;
}
$BookTitle = mysql_real_escape_string($BookTitle);
$q="Select Reviews from Users_Booklist where (Book_Title like '%" .$BookTitle."%');";
if(!mysql_query($q,$con))
{
die("Error".mysql_error());
}
else
{
$row = mysql_fetch_row($q);
?>
<html>
<head><title>Delete Review </title>
</head>
<body>
<br>
<form name="DeleteReview " action="DeleteReviewsFunction.php" method="post">
Review: <input type="text" name="Review" size="200" value="<?php echo $row[0]; ?>"/>
<input type="submit" value="Delete Review" />
</form>
</body>
</html>
<?php
}
}
GetReview($_POST['BookTitle'])
However, it leads me to the next form with nothing in the input text and this warning:
Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\GetReview.php on line 20
I've searched and tried different code but still same result.
Could anyone please tell me where the error is???... Thanks
$qq = mysql_query($q,$con);
if(!$qq) {
// (...)
$row = mysql_fetch_row($qq);
I'm not going to be a lot of help, but your question seems to be where the error is occuring, and I can tell you that.
It's in the $row = mysql_fetch_row($q); line.
You can tell this because the error record starts with mysql_fetch_row(), and the above line is the only mention of mysql_fetch_row() in the code.
Check the SQL query by printing the output of $q variable with:
echo $q;
Now, try to execute it from your MySQL client. Collect the results (if there are) and check for errors.
A suggestion: If you want, you can use a tool like ezSQL that can be very useful (especially for code organization)
not sure how feasable this is, but I have just rolled my own user search form, which simply queries my database and returns all the results with any given username, or similar using the LIKE 'some_username%' statement.
My search works great, and im really chuffed with myself as I am a php and mysql novice.
I used a mysql_fetch_assoc($result) statement, and then used a while loop to echo out each row from the database into an html table.
What I would then like to be able to do, is select a record from the table, and open a new page, which is populated with all the fields for that record, which I can then use to edit and update the user settings.
I thought perhaps one way to do it, is to perhaps echo out a form instead? that way I can have a button next to each row, to post the fields into some php code on my new page? I thought this may be a bit clunky though, and not sure how I would go about echoeing out a different form for each row.
Don;t know if anyone had any ideas on the best way to do this? If you need any code examples of what im working with, I can post them here.
Thanks very much!!
Eds
not a form but a hyperlink.
I wonder why you aren't familiar with this way of opening new pages as it is used everywhere.
just create a hyperlink
name
here is a sketch example of such an application, editing only one field, but you can add any number as well:
a main script:
<?
mysql_connect();
mysql_select_db("new");
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') { //form handler part:
$name = mysql_real_escape_string($_POST['name']);
if ($id = intval($_POST['id'])) {
$query="UPDATE $table SET name='$name' WHERE id=$id";
} else {
$query="INSERT INTO $table SET name='$name'";
}
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) { //listing part:
$LIST=array();
$query="SELECT * FROM $table";
$res=mysql_query($query);
while($row=mysql_fetch_assoc($res)) $LIST[]=$row;
include 'list.php';
} else { // form displaying part:
if ($id=intval($_GET['id'])) {
$query="SELECT * FROM $table WHERE id=$id";
$res=mysql_query($query);
$row=mysql_fetch_assoc($res);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
?>
and two simple templates responsible for output,
one for the displaying the form, form.php
<? include TPL_TOP ?>
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
Return to the list
</form>
<? include TPL_BOTTOM ?>
and one to display the list, list.php
<? include TPL_TOP ?>
Add item
<? foreach ($LIST as $row): ?>
<li><?=$row['name']?>
<? endforeach ?>
<? include TPL_BOTTOM ?>
always start php like this <?php, usually php manual configuration do not support short tag like this <?.
for hyperlink just use view record
It is just query string and get id on next page like this
$id = $_GET['id'];
Hope u will understand..
I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app.
I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present,
the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are
obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my
understanding (and guess-ology).
I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php,
etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other.
Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up)
cheers, s
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
and:
<form id="invoiceData" method="post" action="/html/form.php">
When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this:
<form
id="invoiceData"
method="post"
action="/html/form.php?ID=<?php echo $_GET['ID']; ?>"
>
This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure.
Hope this helps!
$_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to
<form id="invoiceData" method="post" action="/html/form.php?ID=12">
Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.