SQL Statement Not Returning Anything - php

I have a form whereby users are required to anwser their own security question before proceeding further. my form is as follows:
<form action="securitychecked.php" method="post">
<table width="70%" border="0">
<tr>
<td><?php $result = mysql_query("SELECT secret_question FROM public WHERE active = 'activated' AND ni = '". $_SESSION['ni']."'")
or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo '<hr><h4>This Person Has Not Setup A Security Question</h4><hr> ';
} else {
while($info = mysql_fetch_array($result))
{
echo $info['secret_question'];
}
}?></td>
<td><span id="sprytextfield1">
<input type="text" name="secret_answer" id="secret_answer" />
<span class="textfieldRequiredMsg">*</span></span></td>
</tr>
<tr>
<td> </td>
<td><br /><input name="" type="submit" value="Continue" /></td>
</tr>
</table>
</form>
my php code looks like this:
<?php
$secret_anwser=$_POST['secret_anwser'];
$secret_anwser = stripslashes($secret_anwser);
$secret_anwser = mysql_real_escape_string($secret_anwser);
$sql="SELECT secret_anwser FROM public WHERE secret_anwser ='$secret_anwser' AND active = 'activated' AND ni = '". $_SESSION['ni']."'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
header("location:votenow.php");
}
?>
I have a table called public and a field called 'secret_anwser' but i keep on getting a blank page even with the right value being entered. can anyone help me?
thanks

I guess all the secret_anwser in your PHP are typo's.
At least the fields name is secret_answer but you try to get $_POST['secret_anwser']; , you'll never find anything inside the DB.
The names of the DB and the table also may be wrong.

Related

Failing to update the new data entered by administrator

Look like everything is working fine with this code but in fact fails to update the database, Data are displayed correctly while fetching data but when i press update Button the data disappear but no update has been executed. It look fine to me but seems i am wrong.
This is a project for my professor so i don't care for the SQL injection and others.
<html>
<head>
<link rel="stylesheet" type="text/css" href="btnstyle.css">
<title>Managament System</title>
</head>
<body>
<h1>TU Chemnitz Student managament system</h1>
<br>
ADD Person
Edit Person
Manage Boards
Manage Departments
Search N&S
Triple Search
Membership
<br>
<br>
<?php
// set database server access variables:
$host = "localhost";
$user = "";
$pass = "";
$db = "";
// open connection
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!");
// select database
mysql_select_db($db) or die ("Unable to select database!");
// create query
$querys = "SELECT * FROM tblperson";
// execute query
$result = mysql_query($querys) or die ("Error in query: $query. ".mysql_error());
echo "<table border=1 align=center>
<tr>
<th>Personal ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Deparment</th>
<th>Board</th>
<th>Marticulation Number</th>
<th>Reg Date</th>
<th>Action</th>
</tr>";
while($row = mysql_fetch_array($result)) {
?>
<?php
echo '<tr>';
echo '<td>'. $row['personid'].'</td>';
echo '<td>'. $row['personname'].'</td>';
echo '<td>'. $row['personsurname'].'</td>';
echo '<td>'. $row['persondepartment'].'</td>';
echo '<td>'. $row['personboard'].'</td>';
echo '<td>'. $row['martinumber'].'</td>';
echo '<td>'. $row['personregdate'].'</td>';
echo '<td>'.' EDIT '.'</td>';
}
?>
</body>
</html>
and this is the edit file which seems to problematic.
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid'];
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
<form action="edit20.php" method="POST">
<table border="0">
<tr>
<td>First Name</td>
<td><input type="text" name="newpersonname" value="<?php echo $row[1];?>" maxlength="30" size="13"></td>
</tr>
<tr>
<td>Last Name</td>
<td> <input type="text" name="personsurname" value="<?php echo $row[2];?>" maxlength="30" size="30"></td>
</tr>
<tr>
<td>Department</td>
<td>
<select name='persondepartment'>
<option>Production</option>
<option>Sales</option>
</select>
</td>
</tr>
<tr>
<td>Board</td>
<td>
<select name='personboard'>
<option>Evaluation</option>
<option>Executive</option>
<option>Research</option>
</select>
</td>
</tr>
<tr>
<td>Marticulation Number</td>
<td> <input type="text" name="martinumber" maxlength="60" size="30"></td>
</tr>
<tr>
<td>Date of Registration</td>
<td><input type="date" name="personregdate" maxlength="7" size="7"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value=" Update"></td>
</tr>
</table>
</form>
You are looking for personid when the Update button is pressed on the form in edit20.php but that value has never been set so it will be empty and the update will fail.
After
<form action="edit20.php" method="POST">
add:
<input type="hidden" name="personid" value="<?php echo $personid; ?>">
On edit page seem your confusing the same variable with different values. If you state $personid variable to contain the edit value from get, then just re-use the variable don't assign new value. On this line you assign new value :
$personid = $_POST['personid'];
Don't assign new value since it has the initial value already to use just set the variable global for usage
$personid = $_GET['edit'];
Or else create a hidden element and pass edit value into it.
Please add name attribute for your update button
<td colspan="2"><input type="submit" name="update" value=" Update"></td>
and chk whether the update button set or reset as in the place of
if(isset($_POST['newpersonname'])) // change text 'newpersonname' as 'update'
You use a variable that doesn't excist:
<?php
include_once('coneksioni.php');
if(isset($_GET['edit']))
{
$personid = $_GET['edit'];
$res = mysql_query("SELECT * FROM tblperson WHERE personid='$personid'");
$row = mysql_fetch_array($res);
}
if(isset($_POST['newpersonname']))
{
$newpersonname = $_POST['newpersonname'];
$personid = $_POST['personid']; // this doesn't excist
$sql = "UPDATE tblperson SET personname = '$newpersonname' WHERE personid = '$personid'";
$res = mysql_query($sql) or die ("Cant be updated");
echo "< meta http-equiv='refresh' content='0;url=home.php'>";
}
?>
$personid = $_POST['personid']; doesn't excist in your code. Its simply a piece of code you put in there to probably proces, but forgot to define the variable in the code. Place the following in your form.
<input type="hidden" name="personid" value="<?php echo $_GET['edit']; ?>">
You only use this just once because you send the form back after proces to your home, hence it wont be used anymore. You can also use the avariable you defined as $personid; on that position.
If that fails, something maybe wrong in your query. Try to echo out the query (remove qucikly the meta command) by simply just do echo $sql after you do the sql query. 9 out of 10 times, it's a typo.

DB Not updating value upon submit

I have a small issue with updating my database upon a submit.
I have the following in my Database:
a varchar called iUserCash.
Upon login I would like to edit this row in my database table.
The html looks like this:
<form method="post">
<table class="sign_up_form" align="center" width="30%" border="0">
<tr>
<td>
<input type="text" name="cashBalance" placeholder="Nye beløb"/>
</td>
<td>
<button type="submit" name="btn-update" class="betting-btn">OPDATER</button>
</td>
<td>
</tr>
<tr>
</tr>
</table>
</form>
And my sql looks like this:
session_start();
include_once 'controllers/dbConnect.php';
if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
$res=mysql_query("SELECT * FROM oneusers WHERE iUserId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
if(isset($_POST['btn-update']))
{
$ucash = mysql_real_escape_string($_POST['cashBalance']);
if(mysql_query("UPDATE oneusers SET iUserCash = '$ucash' WHERE iUserId='$res'"))
{
?>
<script>alert('successfully registered ');</script>
<?php
}
else
{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
It returns the success message just fine, but it just doesnt update anything. Can anyone tell me what I am doing wrong? :)
Thanks in advance.
you have a error at
mysql_query("UPDATE oneusers SET iUserCash = '$ucash' WHERE iUserId='$res'")
you are using $res for iUserId but it's a db resource...
it seems that, $_SESSION['user'] is the id that you need in query... so try it like
mysql_query("UPDATE oneusers SET iUserCash = '$ucash' WHERE iUserId=" . $_SESSION['user']);

MySQL UPDATE query problems

I have a super easy question. I have a form that echoes out a mySQL record that the user can update. I make my changes, and it tells me that the update is successful, but when I look at the table, the changes do not go through. What is the problem here?
This is the first script.
<?php
require_once("models/config.php");
?>
<table border=1>
<tr>
<td align=center>Edit Form</td>
</tr>
<tr>
<td>
<table>
<?
$personid=$_SERVER['QUERY_STRING'];
$order = "SELECT * FROM persons where personid='$personid'";
$result = mysqli_query($mysqli,$order);
$row = mysqli_fetch_array($result);
?>
<form method="post" action="edit_data.php">
<input type="hidden" name="id" value="<? echo "$row[personid]"?>">
<tr>Person ID:<? echo "$row[personid]"?></tr>
<tr>
<td>First Name</td>
<td>
<input type="text" name="firstname"
size="20" value="<? echo "$row[firstname]"?>">
</td>
</tr>
<tr>
<td>Surname</td>
<td>
<input type="text" name="surname" size="40"
value="<? echo "$row[surname]"?>">
</td>
</tr>
<tr>
<td align="right">
<input type="submit"
name="submit value" value="Edit">
</td>
</tr>
</form>
</table>
</td>
</tr>
</table>
</body>
</html>
Which then goes through to this:
<?
require_once("models/config.php");
$personid = $_POST['personid'];
$firstname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['firstname']));
$surname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['surname']));
$order = "UPDATE persons SET firstname='$firstname', surname='$surname' WHERE personid='$personid'";
$result = mysqli_query($mysqli,$order);
if (!$result) {
echo "Error entering data! <BR>";
echo mysql_error();
} else {
echo "User updated to $firstname $surname <BR>";
}
?>
Is there something I am missing here?
Thanks in advance.
You are sending a hidden input named id and trying to use a $_POST['personid']
correct that
You may also pay attention to the comments you had (SQL Injection's one at least)
Your form sends the id in the field id, while you refer to it as personid.
The reason why this appears to be working, is that the update in itself is correct. $personid is treated as an empty string, so the update correctly updates all records that have an empty personid, which is no record at all.
OK, so here is a revised script with prepared statements. The script is working in the sense that updates are being made to the records. Two questions:
1) is this safe from My-SQL injections?
2) This is updating records successfully, but now it is echoing out "Error entering data!", how come?
<?
require_once("models/config.php");
$personid = $_POST['personid'];
$firstname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['firstname']));
$surname = mysqli_real_escape_string($mysqli, htmlspecialchars($_POST['surname']));
$order = "UPDATE persons SET firstname=?, surname=? WHERE personid=?";
$stmt = mysqli_prepare($mysqli, $order);
mysqli_stmt_bind_param($stmt, "ssi", $_POST['firstname'], $_POST['surname'], $_POST['personid']);
mysqli_stmt_execute($stmt);
$result = mysqli_query($mysqli,$stmt);
if (!$result) {
echo "Error entering data! <BR>";
echo mysqli_error($mysqli);
} else {
echo "User updated to $firstname $surname <BR>";
}
?>
I'm sure the second question is a rather boneheaded one - do I just reverse the conditions?

Blank screen when updating data in php table

I have been working on a project and i am at the final stages of the project. My problem is whenever i try to update data in my database table into returns a blank screen with no error messages. Please find the php script and html form (the form responsible for updating the database table) below, i have divided it into about four sections:
Thanks in advance
Update Form:
<a name="inventoryEditForm" id="inventoryEditForm"></a>
<h3>↓Add New Question Form↓</h3>
<form action="inventory_edit.php" enctype="multipart/from-data" name="myForm" id="myForm" method="post">
<table width="80%" border="0" cellspacing="3" cellpadding="7">
<tr>
<td width="20%"> </td>
<td width="80%"> </td>
</tr>
<tr>
<td>Question</td>
<td><textarea rows="" name="question" cols=""><?php echo $question; ?></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Venue</td>
<td><input type="text" name="venue" maxlength="50" value="<?php echo $venue; ?>"></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="questiondate" value="<?php echo $date; ?>"></td>
</tr>
</table>
<br>
<input name="thisID" type="hidden" value="<?php echo $targetID; ?>"/>
<input type="submit" name="submit" value="Update Question">
<input type="reset" name="clear" value="Clear Form">
</form>
PHP Script:
<?php
//Error reporting due to long script
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
error_reporting(E_PARSE);
//Update question table
If (isset($_POST['question'])) {
$id = mysqli_real_escape_string($link, $_POST['thisID']);
$question = mysqli_real_escape_string($link, $_POST['question']);
$venue = mysqli_real_escape_string($link, $_POST['venue']);
$date = mysqli_real_escape_string($link, $_POST['questiondate']);
//Update question in the table
$sql = mysqli_query($link, "UPDATE DebateQuestion SET question='$question',venue='$venue',date='$date' WHERE qQuestionNo='$id'LIMIT 1") or die(mysql_error());
header("location: inventory.php");
exit();
}
?>
<?php
error_reporting(E_PARSE);
//Gather this questions full information and insert automatically into the edit form
if (isset($_GET['qid'])) {
$targetID = $_GET['qid'];
$sql = mysqli_query($link, "SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1") or die(mysql_error());
$questionCount = mysqli_num_rows($sql); // count the output amount
if ($questionCount > 0) {
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {
$id = $row["qQuestionNo"];
$question = $row["qQuestion"];
$venue = $row["qDebateVenue"];
$date = strftime("%b %d, %Y", strtotime($row["qDate"]));
}
} else {
echo "Oops, no questions like that exists. Check <a href='inventory.php'>inventory</a>again";
exit();
}
}
?>
In your update query you have the data column without using ` back ticks , date is also a mysql's function try to wrap up your column names with back ticks if you are not sure whether they conflict with mysql's reserved keywords
$sql = mysqli_query($link,"UPDATE DebateQuestion SET
`question`='$question',`venue`='$venue',`date`='$date'
WHERE qQuestionNo='$id'LIMIT 1")
"SELECT * FROM DebateQuestion WHERE qQuestionNo='$targetID'LIMIT 1"
Here is qQuestionNo column a string type?if not remove quotes around $targetID.
Note : I have not tested the code - just read it on screen.
I've never seen an IF statement capitalized before :
If (isset($_POST['question'])) {
I'd guess this makes a difference however.
There's lots of other weird things going on in your files, but none that should give you white screen. Try lowercase 'I' in your if statement first.
ALSO - re: the UPDATE statement, you are missing a space between the $id and the LIMIT :
**qQuestionNo='$id'LIMIT 1**

Delete multiple rows by selecting checkboxes using PHP

I want to delete multiple rows from my MYSQL database table. I have created this file to select various links and delete them using checkboxes.
This doesn't seem to delete any row. My data is populated in the table. I guess the problem is with my PHP code. Please check the below code and guide me to get out from this...
<html>
<head>
<title>Links Page</title>
</head>
<body>
<h2>Choose and delete selected links.</h2>
<?php
$dbc = mysqli_connect('localhost','root','admin','sample') or die('Error connecting to MySQL server');
$query = "select * from links ORDER BY link_id";
$result = mysqli_query($dbc,$query) or die('Error querying database');
$count=mysqli_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="3" bgcolor="#FFFFFF">
<strong>Delete multiple links</strong>
</td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF">
<strong>Link ID</strong>
</td>
<td align="center" bgcolor="#FFFFFF">
<strong>Link Name</strong>
</td>
<td align="center" bgcolor="#FFFFFF">
<strong>Link URL</strong>
</td>
</tr>
<?php
while ($row=mysqli_fetch_array($result)) {
?>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="checkbox" type="checkbox" value="
<?php echo $row['link_id']; ?>">
</td>
<td bgcolor="#FFFFFF"> <?php echo $row['link_id']; ?> </td>
<td bgcolor="#FFFFFF"> <?php echo $row['link_name']; ?> </td>
<td bgcolor="#FFFFFF"> <?php echo $row['link_url']; ?> </td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" value="Delete">
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
<?php
// Check if delete button active, start this
if(isset($_POST['delete']))
{
$checkbox = $_POST['checkbox'];
for($i=0; $i<count($checkbox); $i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM links WHERE link_id='$del_id'";
$result = mysqli_query($sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo '<meta http-equiv="refresh" content="0;URL=view_links.php">';
}
}
mysqli_close($dbc);
?>
</body>
</html>
You should treat it as an array like this,
<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">
Then only, you can take its count and loop it for deletion.
You also need to pass the database connection to the query.
$result = mysqli_query($dbc, $sql);
Yours did not include it:
$result = mysqli_query($sql);
Use array notation like name="checkbox[]" in your input element. This will give you $_POST['checkbox'] as array. In the query you can utilize it as
$sql = "DELETE FROM links WHERE link_id in ";
$sql.= "('".implode("','",array_values($_POST['checkbox']))."')";
Thats one single query to delete them all.
Note: You need to escape the values passed in $_POST['checkbox'] with mysql_real_escape_string or similar to prevent SQL Injection.
<?php $sql = "SELECT * FROM guest_book";
$res = mysql_query($sql);
if (mysql_num_rows($res)) {
$query = mysql_query("SELECT * FROM guest_book ORDER BY id");
$i=1;
while($row = mysql_fetch_assoc($query)){
?>
<input type="checkbox" name="checkboxstatus[<?php echo $i; ?>]" value="<?php echo $row['id']; ?>" />
<?php $i++; }} ?>
<input type="submit" value="Delete" name="Delete" />
if($_REQUEST['Delete'] != '')
{
if(!empty($_REQUEST['checkboxstatus'])) {
$checked_values = $_REQUEST['checkboxstatus'];
foreach($checked_values as $val) {
$sqldel = "DELETE from guest_book WHERE id = '$val'";
mysql_query($sqldel);
}
}
}
Delete Multiple checkbox using PHP Code
<input type="checkbox" name="chkbox[] value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
$cnt=array();
$cnt=count($_POST['chkbox']);
for($i=0;$i<$cnt;$i++)
{
$del_id=$_POST['chkbox'][$i];
$query="delete from $tablename where Id=".$del_id;
mysql_query($query);
}
}
Something that sometimes crops up you may/maynot be aware of
Won't always be picked up by by $_POST['delete'] when using IE. Firefox and chrome should work fine though. I use a seperate isntead which solves the problem for IE
As for your not deleting in your code above you appear to be echoing out 2x sets of check boxes both pulling the same data? Is this just a copy + paste mistake or is this actually how your code is?
If its how your code is that'll be the problem as the user could be ticking one checkbox array item but the other one will be unchecked so the php code for delete is getting confused. Either rename the 2nd check box or delete that block of html surely you don't need to display the same list twice ?
$deleted = $_POST['checkbox'];
$sql = "DELETE FROM $tbl_name WHERE id IN (".implode(",", $deleted ) . ")";

Categories