MySQL query not working with PHP from $_GET - php

I cannot seem to pass $_GET into my MYSQL query. Lets say I have 2 tables in my DB, example1 and example2. I would like to query the table selected from the previous page. If I simply put the table into the query it runs fine. Here is what I have so far...
<html>
<form id="area" name="area" method="GET" action="test.php">
Select:
<select id="area" name="area">
<option value="example1">Example1</option>
<option value="example2">Example2</option>
</select><br><br>
<input type="submit" value="Submit">
</form>
</html>
test.php
include "connect.php";
$area = $_GET['area'];
$sql = "SELECT * FROM '$area' ";
$query = mysqli_query($sql);
if (isset($_POST['searchquery'])) {
$search_term = $_POST['searchquery'];
$result = mysqli_query($con, $sql);
}
?>
<strong>Search</strong>
<p>
<form action="test.php" method="POST">
Search: <input type="text" name="searchquery" />
<input type="submit" name="searchname" value="Search">
</form>
<table class="sortable.js" width="100%" cellpadding="1" cellspace="0">
<tr>
<td><strong>1</strong></td>
<td><strong>2</strong></td>
<td><strong>3</strong></td>
<td><strong>4</strong></td>
</tr>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['1']; ?>
<td><?php echo $row['2']; ?>
<td><?php echo $row['3']; ?>
<td><?php echo $row['4']; ?>
<?php } ?>
</table>
If I echo $area it will show properly.

Your table name is quoted. Either remove the quote or use escape character like tick
$sql = "SELECT * FROM `$area` ";

Unlike mysql_(), mysqli_ functions require the connection to be specified explicitly. On the statement $query = mysqli_query($sql); you used msqli_ but you didn't provide the connection (mysqli link resource variable ) you should pass in the connection as the firs parameter of the call like this $query = mysqli_query($connection, $sql); . And also, don't forget to select a database. you can select a database like this. mysqli_select_db($connection,"database_name"); Remember to replace $connection with your connection variable name.

I found that the following was the solution to my problem.
I changed:
<form action="test.php" method="POST">
to
<form action="test.php?area=<?php echo $area?>" method="POST">
Thanks for everyone help!

Related

Editing php / mysql table but does not update table

I am trying to edit a mysql table, however when i submit the form, the table does not get updated, and the previous value remains the same. I am not getting any errors at all either...
i have tried running the update query directly in the database, and it works...can someone have a look at my code and see if they can help?
below is my code:
edit.php
<?php include('server.php') ?>
<?php
if(isset($_POST['update']))
{
$responseid = $_POST['responseid'];
$response=$_POST['response'];
{
//updating the table
$result = $conn->prepare ("UPDATE response SET response= '$response' WHERE responseid=$responseid");
header("Location: results.php");
}
}
?>
<?php
//getting id from url
$responseid = $_GET['id'];
//selecting data associated with this particular id
$result = $conn->prepare("SELECT * FROM response WHERE responseid=$responseid");
while ($response = $result->fetch())
{
$response = $res['response'];
$student_id = $res['student_id'];
}
?>
<html>
<head>
<title>Edit Data</title>
</head>
<body>
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>response</td>
<td><input type='text' name='date' value="<?php echo $response;?>"</td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
results.php
<div id="table1" class="table1">
<?php
if(isset($_POST["submit"]))
{
$searchTerm=$_POST['search'];
$stmt = $conn->prepare(" SELECT question.description AS question, answer.description AS answer, discipline.name AS name, response.responseid AS responseid, response.response AS response, response.student_id AS student_id, response.Date_Time AS Date
FROM response
INNER JOIN answer ON response.question_id = answer.answerid
INNER JOIN question ON response.question_id = question.qid
INNER JOIN discipline ON response.discipline_id = discipline.disciplineid WHERE Date_Time LIKE :searchTerm");
$stmt->bindValue(':searchTerm','%'.$searchTerm.'%');
$stmt->execute();
$result=0;
/*
The above code is a query which selects attributes according to the search term
*/
echo "<table> <tr><th>Discipline</th><th>Question</th><th>Student ID</th><th>Response</th><th>Date & Time</th><th>Answer</th><th>Final Marks</th></tr>";
while ($response = $stmt->fetch()) /* This is a While loop which iterates each row */
{
echo " <tr><td>".$response["name"]."</td><td>".$response["question"]."</td><td>".$response["student_id"]."</td><td>".$response["response"]."</td><td>".$response["Date"]."</td><td><input type='text' name='date' value=". $response["answer"]."></td><td>Edit</td></tr> ";
$result++;
}
} /* This bit of code closes the connection with the database */
?>
</div>
please click this link to see my database
Updating using prepared statements (similar to the way your doing it in the select in the second listing)...
//updating the table
$result = $conn->prepare ("UPDATE response
SET response= :response
WHERE responseid=:responseid");
$result->bindValue(':response',$response);
$result->bindValue(':responseid', $responseid);
$result->execute();
Also check the contents of $_POST as I think you have the field names wrong (think they were 'date' and 'id')...
<form name="form1" method="post" action="edit.php">
<table border="0">
<tr>
<td>response</td>
<td><input type='text' name='response' value="<?php echo $response;?>"</td>
</tr>
<tr>
<td><input type="hidden" name="responseid" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>

Multiple row insert to table if check box is selected

I am trying to insert multiple rows to a database table if check box is selected. But in my code when I am trying to insert, new rows are inserting based on check box selection. But no data is passing. I need some advice on below code to modify:
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$qry="select * from pi";
$result=mysql_query($qry);
?>
<form action="check.php" method="post">
<table>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
<?php
while($row=mysql_fetch_array($result))
{
echo "<tr><td><input type=checkbox name=name[] value='".$row['id']."'>".$row['PI_NO']."</td><td>".$row['CUSTOMER_NAME']."</td><td>".$row['PI_ADDRESS']."</td></tr>";
}
?>
<input type="submit" value="save" id="submit">
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$name=$_POST['name'];
foreach($_POST['name'] as $x)
{
$qry="INSERT INTO pi (PI_NO, CUSTOMER_NAME, PI_ADDRESS)VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
}
?>
Notes:
You forgot to bind the name of your checkbox using a single tick (')
You used variables in your query which you didn't defined and assigned value with yet
You only passed on the value of name, and did not include the Pi Address and Customer name. I'll be passing them by hidden input using <input type="hidden">.
I'll change the way you check your passed on form by looping them and check them using for() and if()
Use mysql_real_escape_string() before using them in your queries to prevent some of the SQL injections. But better if you consider using mysqli prepared statement rather than the deprecated mysql_*.
Is your post a single file? If it is, you must enclose your query using an isset() to prevent error upon loading the page.
You didn't close your <form>
Here's your corrected while loop:
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td>
<input type="checkbox" name="name[]" value="<?php echo $row['id']; ?>">
<?php echo $row["PI_NO"]; ?>
<!-- HERE IS THE START OF YOUR TWO HIDDEN INPUT -->
<input type="hidden" name="piaddress[]" value="<?php echo $row["PI_ADDRESS"]; ?>">
<input type="hidden" name="customer[]" value="<?php echo $row["CUSTOMER_NAME"]; ?>">
</td>
<td><?php echo $row['CUSTOMER_NAME']; ?></td>
<td><?php echo $row['PI_ADDRESS']; ?></td>
</tr>
<?php
} /* END OF WHILE LOOP */
?>
<input type="submit" value="save" id="submit">
</form> <!-- YOU DID NOT CLOSE YOUR FORM IN YOUR POST -->
And your query:
<?php
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$counter = count($_POST["name"]); /* COUNT THE PASSED ON NAME */
for($x=0; $x<=$counter; $x++){
if(!empty($_POST["name"][$x])){
$PI_NO = mysql_real_escape_string($_POST["name"][$x]);
$CUSTOMER_NAME = mysql_real_escape_string($_POST["customer"][$x]);
$PI_ADDRESS = mysql_real_escape_string($_POST["piaddress"][$x]);
$qry="INSERT INTO pi (PI_NO, CUSTOMER_NAME, PI_ADDRESS) VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
} /* END OF CHECKING THE CHECKBOX IF SELECTED */
} /* END OF FOR LOOP */
?>
Lots of little problems. And some big ones.
as $x){ .. $x is not being used so I assume you just loop for the number of checked boxes.
These have no values: '$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS'
Missing </form>
Not being used: $name=$_POST['name'];
<?php
echo '<form action="check.php" method="post"><table><tr><th>A</th><th>B</th><th>C</th></tr>';
$db=mysql_connect("localhost","root","");
mysql_select_db("kkk",$db);
$sql = "select `id`,`PI_NO`, `CUSTOMER_NAME` ,`PI_ADDRESS` from `pi`";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
echo "<tr><td><input type=\"checkbox\" name=\"name[]\" value=/"$row[0]/"'>$row[1]</td><td>$row[2]</td><td>$row[3]</td></tr>";
}
echo '<input type="submit" value="save" id="submit"></form>';
foreach($_POST['name'] as $x){
$sql="INSERT INTO pi (`PI_NO`, `CUSTOMER_NAME`, `PI_ADDRESS`)VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($sql);
}
?>

How to make value in form POST to same page?

I have to make everything happened on the same page. I have used action="<?PHP echo $_SERVER['PHP_SELF']; ?>" here but it is not working. I have insert the PHP query below the form. Basically, my question is how do I make sure the form is posting the values on the same page. If it is updated, a pop up will come up.
$user_id=$_SESSION['user_id'];
$date = date("l jS \of F Y h:i:s A");
$query1 ="SELECT daily_limit FROM user WHERE user_id='$user_id'";
$result1 = mysqli_query($link, $query1) or die(mysqli_error($link));
while ($row1 = mysqli_fetch_array($result1)) {
$dailylimit=$row1['daily_limit'];
}
$query2 = "SELECT SUM(debit) AS debited_today FROM transaction WHERE user_id = '$user_id' AND date = CURRENT_DATE" ;
$result2 = mysqli_query($link, $query2) or die (msqli_error($link));
while ($row2 = mysqli_fetch_array($result2)){
$debited_today = $row2['debited_today'];
}
// form
<form method="POST" action="<?PHP echo $_SERVER['PHP_SELF']; ?>" >
<table id="table">
<tr>
<td class="alt">Existing Daily Limit</td>
<td>S$ <?php echo $dailylimit; ?> </td>
<input type="hidden" name="dailylimit" value="<?php echo $dailylimit ?> "/>
</tr>
<tr>
<td class="alt"><label for="newdailylimit">New Daily Limit</label></td>
<td>$ <select name="newdailylimit">
<option value="100.00">100.00</option>
<option value="500.00">500.00</option>
<option value="1000.00">1000.00</option>
<option value=5000.00">5000.00</option>
</select></td>
</tr>
<tr>
<td class="alt">Amount Debited Today</td>
<td>S$ <?php echo $debited_today; ?></td>
</tr>
<tr>
<td class="alt">Amount Debited Left</td>
<td>S$ <?php echo ($dailylimit - $debited_today); ?> </td>
</tr>
</table>
<br/>
<input type="submit" name="submit "value="Submit"></input>
</form>
// Values I need to POST
$dailylimit = $_POST['dailylimit'];
$newdailylimit = $_POST['newdailylimit'];
if ($dailylimit != $newdailylimit){
$query = "UPDATE user SET daily_limit='$newdailylimit' WHERE user_id='$user_id'";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
echo "<script>alert('You have successfully updated your daily limit');</script>";
}
else if ($dailylimit == $newdailylimit){
echo "<script>alert('You have selected the same daily limit as your previous one. Please choose a different one. ');</script>";
}
else{
}
Ahh I may have found out what the problem is:
You have a space after the word submit and no space before value.
This will prevent your form from submitting.
<input type="submit" name="submit "value="Submit"></input>
---^ ^
Change this to:
<input type="submit" name="submit" value="Submit">
The double quote might mess things up.
Other things that are wrong but won't fix your problem
Also
<option value=5000.00">5000.00</option>
should be
<option value="5000.00">5000.00</option>
Also
<input type="hidden" name="dailylimit" value="<?php echo $dailylimit ?> "/>
// You have an extra space here ^
Which will change your $dailylimit, and append it with a space.
make your action=''. it will post to itself.
then on top of your page check if the request is post ex. if($_POST){//add your code}else{//yourform}

Flexibility within 'Print/Echo'

I made this code:
<?php if($this->session->userdata('login_user_id'));
$a = $this->session->userdata('login_user_id');
$b = mysql_query("SELECT * FROM user WHERE id='$a' AND specialrank='1'")
or die(mysql_error());
while($c = mysql_fetch_array( $b ))
{
Print $c['username'];
}
?>
basically it creates a session for the logged in user.
I want to be able to show more in the print section though, some advanced php code and html form. Is there a way I can do this by reworking the code? It seems I'm limited with regards to which characters I can use within the print statement.
Basically, I want to display a form to specific users and not others.
I have tried closing the <?php ?> tags after every line to see if that works but it throws up errors of unexpected and expected's etc.
EDIT:
this is the segment of code I want to show:
<?php // update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$emp_salary = $_POST['emp_salary'];
$sql = "UPDATE pins SET is_private = $emp_salary WHERE id = $pinDetails->id";
mysql_select_db('test_db');$retval = mysql_query( $sql );if(! $retval )
{ die('Could not change: ' . mysql_error());
}
echo "Post is now private<br><br>";
}
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Private
<input name="emp_salary" type="text" id="emp_salary" value="1">
<input name="id" type="hidden" id="id">
<input name="update" type="submit" id="update" value="Change">
</td>
</tr>
</table>
</form>
As you can see, simply putting that within the print throws up so many errors.

Updating a table with PHP and MYSQL

<?php require("inc_connect.php"); ?>
<h1 align="center">Farris Website</h1>
<hr width="1000">
<p align="center">
<table align="center" width="1000" border="3" bordercolor="#0066FF" >
<tr>
<td align="left" valign="top">
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_POST['id']); ?>">
<p><strong>Enter Name:</strong>
<input type="text" name="name">
<br />
ID:
<label for="select"></label>
<select name="id">
<?php
$query = "SELECT * FROM test";
$run = mysql_query($query);
while($output = mysql_fetch_array($run)){
echo "<option value=\"{$output['id']}\">{$output['id']}</option>";}
?>
</select>
</p>
<p>
<input type="submit" name="submit" value="Update!">
</p>
</form></td>
<td width="300" align="left" valign="top"><?php include("inc_output.php"); ?></td>
</tr>
</table>
</p>
The above is the index page ...
<?php
$connect = mysql_connect("localhost","root","");
$sel_database = mysql_select_db("test");
$name = mysql_real_escape_string( $_POST["name"] );
$id = (int) $_GET['id'];
$query = "UPDATE test SET name='{$name}'";
if($run = mysql_query($query)){
header("location: index.php");
exit;
}else{mysql_error();}
?>
And this is the page that processes the form.
The problem is that the record won't update if i set the id={$_GET['id']}
and if I remove that part it updates all the rows.
So updating according to id ...
Thanks in Advance
FarrisFahad
Try changing your form action to
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_GET['id']); ?>">
Also, doing an echo of $query might help debug your problem.
First, just be aware of SQL Injection - your code is wide open to it. See http://bobby-tables.com/
PHP Code
<?php
$connect = mysql_connect("localhost","root","");
$sel_database = mysql_select_db("test");
$name = mysql_real_escape_string( $_POST["name"] );
$id = (int) $_GET['id'];
$query = "UPDATE test SET name='{$name}' WHERE id = {$id}";
if($run = mysql_query($query)){
header("location: index.php");
exit;
}else{
# In production, don't show raw errors to users - log them to a file and
# present the user with a generic "There was a problem with the database"
# error. Or people can start sniffing for vulnerabilities in your site.
echo mysql_error();
}
?>
Page
<?php
require("inc_connect.php");
?>
<h1 align="center">Farris Website</h1>
<hr width="1000">
<p align="center">
<table align="center" width="1000" border="3" bordercolor="#0066FF" >
<tr>
<td><form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_GET['id']); ?>">
<p><strong>Enter Name:</strong>
<input type="text" name="name"><br />
<label for="select">ID:</label>
<select name="id" id="select">
<?php
$query = "SELECT * FROM test";
$run = mysql_query($query);
while( $r = mysql_fetch_array($run) ){
# I always use short, single character, variables when in loops.
# Saves alot of characters and potential confusion.
echo " <option value='{$r['id']}'>{$r['id']}</option>\n";
}
?>
</select>
</p>
<p>
<input type="submit" name="submit" value="Update!">
</p>
</form></td>
<td><?php include("inc_output.php"); ?></td>
</tr>
</table>
</p>
As you want to update that record which is selected from your dropdown. Moreover u have set your form method to POST. So you should try following:
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_POST['id']); ?>">

Categories