How to make this MySQL query using variables to work? - php

I have a form which sends a Roll_No value using post method to a php file:
//Query the database
$resultSet = $mysqli->query("SELECT * FROM late WHERE 'Roll_No' LIKE '" . $_POST['Roll_No'] . "';");
//Count the returned rows
if($resultSet->num_rows != 0){
//Turn the results into an array and echo them
while($rows = $resultSet->fetch_assoc())
{
$Roll_No = $rows['Roll_No'];
$Time = $rows['Time'];
echo "<p>Roll_No: $Roll_No <br />Time: $Time</p>";
}
My code seems to be unable to take the Roll_No value from the form and therefore gives no results.
EDIT: Here's the form
<form action="report-d1.php" method="post" />
<p>Search by Roll_No<input type="text" name="Roll_No" /></p>
<input type="submit" value="Submit" />
</form>

Related

Submit data into table based on certain input field in HTML form

I am currently creating a survey where the answers are entered into a database.
I have 2 main tables:
questions, with 2 columns: questionID and questionBody
answers, with 3 columns: answerID, questionID (I want this to be tied to the column in table questions) and answerBody.
On the HTML page I am planning to create there will be multiple questions with multiple text boxes to fill in correlating to each quesiton. Is it possible that when the person submits the form, the answers are inserted into table answers with the questionID being based on what field was filled out?
So for example, If I have questionBody as "What is this Question asking?" and the questionID as 1 in table questions, when I submit the form I want table answers to also have questionID 1 in there.
At the moment this is my code:
//Check if error variables have any values assigned
if (empty($answerError))
{
//Prepare database insert
$sql = "INSERT INTO answers (questionID, answerBody) VALUES (?,?)";
//Check if the statement has the connect and sql variables
if ($statement = mysqli_prepare($connect, $sql))
{
//Add variables to the statement
mysqli_stmt_bind_param($statement, "ss", $paramQuestion, $paramAnswer);
//Set the parameter to the answer
$paramQuestion = getQuestionName($connect);
$paramAnswer = $answer;
//Execute statement with entered variable
if (mysqli_stmt_execute($statement))
{
//Redirect user to success page
header("location: thankyou.php");
}
else
{
echo "Something went wrong. Please try again later.";
}
//Close statement
mysqli_stmt_close($statement);
}
}
and for the function getQuestionName():
function getQuestionName($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$questionID = $row['questionID'];
return $questionID;
}
}
}
The code I am using to output the form into a HTML page is:
function getQuestions($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$body = $row['questionBody'];
echo '<div class="entry">
<div class="questionTitle"><h3>' . $body . '</h3>
<form action="survey.php" method="POST">
<input type="text" name="answer" size="50" />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</div>';
}
}
Any help on this would be greatly appreciated :)
Yes it's completely possible. Just put the question ID as a hidden field in the form, and it will be submitted along with the answer data when the form is submitted. Then you can retrieve it from the $_POST data just like the answer, and use it in your SQL query.
For example:
HTML form:
<form action="survey.php" method="POST">
<input type="hidden" name="questionID" value="<?php echo $row["questionID"]; ?>" />
<input type="text" name="answer" size="50" />
<input type="submit" value="Submit" name="submit" />
</form>
survey.php:
$paramQuestion = $_POST["questionID"];
From your question, I will suggest you make use of input with a hidden attribute.
something like this
<input type='text' name='question-id' value="<?php echo $questionId ;?>" hidden>
The user doesn't see the input it get filled from whatever you are providing into it.
Editing your code, you should do something like this.
function getQuestions($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$body = $row['questionBody'];
$questionId = $row['questionId'];
echo '<div class="entry">
<div class="questionTitle"><h3>' . $body . '</h3>
<form action="survey.php" method="POST">
<input type="text" name="answer" size="50" />
<input type="number"name="question-id" value="'.$questionId.'" hidden>
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</div>';
}
}

search for a specific row in MySQL using PHP

I'm trying to verify my search box (html) using php code
but in all times it gives all rows I dont know where is the problem
html code:
<form action="searchHotel.php" method="post">
<input value="Hotel's Name" type="text" name="Hotels_Name" id="dropdownlist" style="width:150px; hight:10px;">
</form>
</br>
<br/>
<button style = " margin-top:2%; position:relative;" type="button" onClick="location.href='searchHotel.php'" method="post" action="searchHotel.php">GO</button>
<br/><br/>
a peice of php code:
//code
echo $_POST['Hotels_Name'];
$n = (string) $_POST['Hotels_Name'];
$variable = (string)$n;
$query = "SELECT * FROM facility WHERE name LIKE '%$variable%'";
$result = mysql_query($query) or die('Query failed: ' . mysql_error() . "<br />\n$sqlquery");
$number = mysql_num_rows($result);
echo $number;
$row = mysql_fetch_assoc($result);
print_r($row);
I have already connected the database
Correct your html code use below code. In your code there is no proper form action onto form. So try below html code. Also try mysqli for database operations in php code.
<form action="searchHotel.php" method="post">
<input type="text" name="Hotels_Name" id="dropdownlist" style="width:150px; hight:10px;">
<input style = " margin-top:2%; position:relative;" type="submit" value="GO" >
</form>

If content exists in database, provide form to update it - else provide form to add new row

It's all going wrong. I need to output a form onto my website that will do 1 of 2 things:
If the user already has content in the database, provide a form that posts to self to update the existing content.
If the user does not have content in the database, provide a form to let the user add information to the database.
The forms should submit to themselves to keep coding tidy. I'm getting into a right mess. I'll show what I have so far, but I'm getting in a muddle.
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
while($row = mysql_fetch_array($result))
{
$profileText = $row['text'];
}
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
echo
'<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">' .
$profileText .'
</textarea><br />
<input type="submit" value="Submit" />
</form>'
;}
else{
$profileText = $row['text'];
echo
"<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>" .
$profileText
."</textarea><br />
<input type='submit' value='Submit' />
</form>"
;}?>
You've pretty much got the functionality there, just needs tidying up.
Try something like this:
<?php
//look in db to see if content exists, if it does set variable
$profileText="";
if($result = mysql_query("SELECT * from tbl_profiles WHERE user_id = $who")) {
while($row = mysql_fetch_array($result))
{
$profileText .= $row['text'];
}
?>
<form action="../edit/indexUpdate.php" method="post" name="edit">
Comments:<br />
<textarea name="updatedText" id="comments">
<?php echo $profileText; ?>
</textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
} else {
?>
<form action='../edit/index.php' method='post' name='add'>
Comments:<br />
<textarea name='comments' id='comments'>
<?php echo $profileText; ?>
</textarea><br />
<input type='submit' value='Submit' />
</form>
<?php
}
?>
The basic idea is to add a record if new and update if not. What you can do is use an id to represent the record or -1 if it's a new entry
Something along the lines of:
//Defaults
$recordid=-1;
$name='';
$comments='';
//look in db to see if content exists, if it does set variable
$result = mysql_query(
"SELECT * from tbl_profiles
WHERE user_id = $who
");
// Check if user has content in db
$result = mysql_query(
"SELECT * FROM tbl_profiles WHERE user_id='$who'");
if(mysql_fetch_array($result) !== false){
//Yes. Get the id
$recordid = $result->id;
//Get the values
$name= $result->name;
$comments= $result->name;
}
<form action="../edit/index.php" method="post" name="formdata">
<input type="hidden" name="recordid" value="<? echo htmlspecialchars($recordid) ?>">
<input type="hidden" name="name" value="<? echo htmlspecialchars($name) ?>">
<textarea name="comments" id="comments"><? echo htmlspecialchars($comments) ?></textarea>
<input type="submit" value="submit"/>
</form>
This way a new form will have a -1 but an existing will have an id.
As an additional point it is very important to sanitize your inputs for SQL and what you output in HTML to stop SQL Injections. For your reference on this:
SQL
Little Bobby Tables
Cross Site Scripting

Unable to edit mysql row using form

I am trying to create a form that will edit rows from my db table. (Based on some code I got from a StackOverflow page.)
I am able to populate the form with relevant data, but when I submit the form, the row isn't updated. In fact, some of my columns are deleted.
What did I do wrong?
edit.php
<?php
$UID = (int)$_GET['f'];
$query = mysql_query("SELECT * FROM user_feeds WHERE feed_id = '$UID'") or die(mysql_error());
if(mysql_num_rows($query)>=1){
while($row = mysql_fetch_array($query)) {
$feedtitle = $row['feed_title'];
$feedurl = $row['feed_url'];
$feedorder = $row['feed_order'];
$feedowner = $row['feed_owner'];
}
?>
<form action="update.php" method="post">
<input type="hidden" name="ID" value="<?=$UID;?>">
Title:<br /> <input type="text" name="ud_feedtitle" value="<?=$feedtitle?>"><br>
URL: <br /> <input type="text" name="ud_feedurl" value="<?=$feedurl?>"><br>
Order: <br /> <input type="text" name="ud_feedorder" value="<?=$feedorder?>"><br>
Owner:<br /> <input type="text" name="ud_feedowner" value="<?=$feedowner;?>"><br>
<input type="Submit">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
</div>
</body>
</html>
update.php
<?php
$ud_ID = $_REQUEST["ID"];
$ud_feedtitle = $_POST["feed_title"];
$ud_feedurl = $_POST["feed_url"];
$ud_feedorder = $_POST["feed_order"];
$ud_feedowner = $_POST["feed_owner"];
$query = "UPDATE user_feeds SET feed_title = '$ud_feedtitle', feed_url = '$ud_feedurl', feed_order = '$ud_feedorder', feed_owner = '$ud_feedowner', WHERE feed_id = '$ud_ID'";
$res = mysql_query($query);
if ($res)
echo "<p>Record Updated<p>";
else
echo "Problem updating record. MySQL Error: " . mysql_error();
?>
Reason:
The name of the input field is the same name by which $_POST is populated. The variables you are currently requesting :
$_POST["feed_title"];, $_POST["feed_url"];, $_POST["feed_order"];, $_POST["feed_owner"];
are all empty as they don't exist. When updating, you are replacing the values in your table with blank values.
Solution:
In your update.php, the following should be there instead.
$ud_ID = $_POST["ID"];
$ud_feedtitle = $_POST["ud_feedtitle"]; //corresponding to <input type="text" name="ud_feedtitle" ...
$ud_feedurl = $_POST["ud_feedurl"]; //corresponding to <input type="text" name="ud_feedurl" ...
$ud_feedorder = $_POST["ud_feedorder"]; //corresponding to <input type="text" name="ud_feedorder" ...
$ud_feedowner = $_POST["ud_feedowner"]; //corresponding to <input type="text" name="ud_feedowner" ...

PHP IF ELSE - If seems to be ignored?

i'm a bit of PHP noob, so sorry if this is a daft question, but I just can't figure this out by myself so any help would be greatly appreciated!
I am trying to create a modify page for an events web application. It seems to be working except when I try to validate the final if/else statement.
This statement returns the value of $row[0] and checks if its == NULL. If NULL, it should return an echo 'this event does not exist' to the user, if there is a value, it presents the user with a matrix of text boxes that they can change the data in.
Currently it works fine for the else statement when there is data found, but doesnt recognise the original if when there is no data. Coupled with that, the footer at the bottom of the page disappears!
Here is the main body of the code, i have highlighted the problem area. I understand that there is probably a more effective and efficient way of doing it all, but please keep it simple as I'm still learning. Thanks again. Dan
<div class="round">
<div id="main" class="round">
<span class="bold">MODIFY EVENT</span><br /><br />
On this page you can modify or delete the events that are stored on the database.<br />
Be aware that you cannot undo the DELETE function.<br />
<br />
Find Event:<br />
<table>
<form name="form1" id="form1" method="post" action="
<?php echo $_SERVER["PHP_SELF"]; ?>" >
<tr><th>By Date:</td><td><input type="text" name="modifyDate"
id="modifyDate" value="dd/mm/yy" /></td></tr>
<tr><th>By Name:</td><td><input type="text" name="modifyName" id="modifyName"
value="" /></td></tr>
<tr><th>Find All:</th><td><input type="checkbox" name="modifyAll"
id="modifyAll" /><td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Search" /></td></tr>
</form>
</table>
<?PHP
if(!isset($_POST['modify'])){
if(isset($_POST['submit'])){
$moddate = $_POST['modifyDate'];
If($moddate == "dd/mm/yy"){
$date = "";
}
else{
$newDate = str_replace("/",".",$moddate);
$wholeDate = $newDate;
$dateArray = explode('.', $wholeDate);
$date = mktime(0,0,0,$dateArray[1],$dateArray[0],$dateArray[2]);
}
$name = $_POST['modifyName'];
$all = $_POST['modifyAll'];
$host = "localhost";
$user = "user";
$password = "password";
$db = "database";
$con = mysql_connect($host,$user,$password) or die('Could not connect to Server');
$dbc = mysql_select_db($db, $con) or die('Could not connect to Database');
if($all != 'on'){
$q = "SELECT * FROM events WHERE date = '$date' || title = '$name' ";
}
else{
$q = "SELECT * FROM events";
}
$result = mysql_query($q);
$row = mysql_fetch_array($result) or die(mysql_error());
//THIS IS THE PROBLEM HERE!!!!
if($row[0]==NULL){
echo 'This event does not exist';
}
else{
?>
<form name="form1" id="form1" method="post" action="
<?phpecho $_SERVER['PHP_SELF']; ?>" >
<?PHP
$result = mysql_query($q) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$initialDate = date('d/m/y', $row['date']);
$ID = $row['ID'];
echo '<input type="text" name="inputEmail" id="inputEmail" value="'.$initialDate.'" />';
echo '<input type="checkbox" value=$ID name="toModify[]" style = "visibility: hidden;" /><br /><br />';
}
echo '<input type="submit" name="modify" value="Modify" />
<br /><br />';
}
}
}
else{
//modify database and return echo to user
}
?>
</div>
<div id="clear"></div>
</div>
</div>
</div>
<div id="footer" class="round shadow"></div>
</body>
</html>
mysql_fetch_array($result) returns false if there are no rows, so it's possible that even if there is nothing in the result, it's still returning a false and your if($row[0] == null) is evaluating to false, also.
In other words, you should be doing a more robust test on the return results from your query to catch fringe cases.
As others have mentioned or implied, here are some things you could / should be doing:
test for rows returned, not values in rows
test for existence of variable, not content of variable
check the database for errors returned
Is the field in the table it's pulling $row[0] from set to NOT NULL? If it is, it will never be a null value. Try instead something like (if empty($row[0]))
You could check the number of result rows to see if there are any events:
$result = mysql_query($q);
$numrows = mysql_num_rows ($result);
if($numrows === 0){
...

Categories