I have a problem with this code, it does delete a row but not editing one. I cannot figure out how to make it work.
Here's the script:
<?php
if($_POST['delete']){
$i = 0;
while(list($key, $val) = each($_POST['checkbox'])) {
$sql = "DELETE FROM $tbl_name WHERE id='$val'";
mysql_query($sql);
$i += mysql_affected_rows();
}
// if successful redirect to delete_multiple.php
if($i > 0){
echo '<meta http-equiv="refresh" content="0;URL=data.php">';
}
}
if($Submit){
for($i=0;$i<$count;$i++){
$sql="UPDATE $tbl_name SET naam='$naam[$i]', achternaam='$achternaam[$i]', leeftijd='$leeftijd[$i]', straat='$straat[$i]', postcode='$postcode[$i]', telefoon='$telefoon[$i]', email='$email[$i]', geslacht='$geslacht[$i]', pakket='$pakket[$i]', WHERE id='$id[$i]'";
$result1=mysql_query($sql1);
}
}
mysql_close();
?>
As others have pointed out $Submit isn't defined before the if statement - also $tbl_name isn't defined either so it would bring back an error if the if statement was triggered.
Also in $result1 you used $sql1 - $sql1 has not been defined.
You're vulnerable to SQL injections like Pekka said, so I advise reading up on it, always, ALWAYS validate user inputted data, never trust anyone :)
Also, you don't need to print a meta refresh, you can just use header
header ("Location: data.php");
$Submit is not defined before it is used. So, its value will be null which is a falsy value. Hence if loop will never get executed.
$Submit is not defined (as others already mentioned). Also, if you do define $Submit then $count is still undefined. So you still won't get into the for loop. And if $count is defined, your code still does not update the database. You store your sql query in $sql but pass $sql1 , which has not been set, as query that should be executed.
And your code is wide open for sql injection. You should not want that.
Related
Im having a problem of accessing the session variable value.
im creating a login page and this were i set the values of my session variables.
index.php
<?php
session_start();
$result=mysql_query("select * from myuser where id='".$id ."' and password='".$password."'");
if(mysql_num_rows($result) > 0){
$user = mysql_fetch_assoc($result);
$_SESSION['SESS_ID'] = $user['id'];
$_SESSION['SESS_UNAME'] = $user['username'];
$_SESSION['SESS_PASS'] = $user['password'];
header("location:home.php");
exit();
}
?>
home.php
<?php
session_start();
if(!isset($_SESSION['SESS_ID']) || (trim($_SESSION['SESS_ID'])) == ''){
header("location:index.php");
exit();
}
?>
<html>
<body>
<p>Login Successful</p>
<?php echo $_SESSION['SESS_ID'] ; ?>
</body>
</html>
the problem here is i have no value in $_SESSION['SESS_ID']..so how do i get or access the value of this session variable in my home.php?
Edit: my query for the SQL is
select * from myuser where id='".$id ."' and password='".$password."'
Some points about why you have this issue:
the values you populate the $_SESSION array with come directly from the database, but you have no database SQL query - instead you have
"!--query written here --"
If you can replace this placeholder with a query that returns your id, username and password values then your code should execute as expected.
I'm not certain if your syntax is wrong as such, but it is not the shape I would ever lay it out, my own shape would be:
$result = mysqli_query($connection, $sql);
while ($outputrow = mysqli_fetch_array($result)){
// In here $outputrow is an array of ONE row of your database, so
// $outputRow['id'] = the id from one row. ordered by the ORDER BY in your SQL query.
}
Add a mysqli_error($connection) clause to your SQL query to detect errors. such as :
Here:
$result=mysqli_query($connection, "<!--query written here -->") or die("error :".mysqli_error($connection));
As I have used across these examples, please, please STOP using MySQL and use at least MySQLi or even PDO. There are a host of improvements and bug fixes and lots of info on this transition on SO.
Also, never, ever compare passwords as strings, passwords saved to a database should as a minimum be saved as hashes with PHP function password_hash(). Never have the line if($_POST['pwd'] == $row['pwd']){.
Finally, as rightly mentioned by Fred-ii- in comments, add error logging and checking into your script so that you know what's going on:
Such as:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Add these to the very top of your PHP page and they will display your errors and warnings to you so you can see what is and is not working.
EDIT:
From your edit there are two biq questions, your statement is that:
"select * from myuser where id='".$id ."' and password='".$password."'
so where does the value $id and $password come from? is the <?php at the top of the page, if so, these variables will always be empty, you need to apply a value to these variables.
<?php
session_start();
if (!isset($_SESSION)){
}
$total_amt=$_POST['total_amt'];
$total_seats=$_POST['total_seats'];
$boarding_point=$_POST['boarding_point'];
$_SESSION['total_amt']=$total_amt;
$_SESSION['total_seats']=$total_seats;
$_SESSION['boarding_point']=$boarding_point;
?>
<?php
require_once("config.php");
$source_point=$_SESSION['source_point'];
$destination=$_SESSION['destination'];
$datepick=$_SESSION['datepick'];
$_SESSION['total_amt']=$total_amt;
$_SESSION['total_seats']=$total_seats;
$boarding_point=$_POST['boarding_point'];
// Insert data into mysql
$sql="INSERT INTO book_seat(from, to, datepick, total_amt, total_seats, boarding_point) VALUES
'{$_SESSION['source_point']}',
'{$_SESSION['destination']}',
'{$_SESSION['datepick']}',
'{$_SESSION['total_amt']}',
'{$_SESSION['total_seats']}',
'{$_SESSION['boarding_point']}')";
$result=mysql_query($sql);
if(isset($_POST['chksbmt']) && !$errors)
{
header("location:booking_detail.php");
}
if(!$sql) die(mysql_error());
mysql_close();
?>
I want to insert my session variables to my database..
This is my code, there is no error happening, page is redirecting to booking_detail.php but also these session variables are not getting inserted to my database also..
From and to are reserved word,use backticks
Reserved words in Mysql
$sql="INSERT INTO book_seat(`from`, `to`, datepick, total_amt, total_seats, boarding_point) VALUES
'{$_SESSION['source_point']}',
'{$_SESSION['destination']}',
'{$_SESSION['datepick']}',
'{$_SESSION['total_amt']}',
'{$_SESSION['total_seats']}',
'{$_SESSION['boarding_point']}')";
Comment out your header(), turn on error reporting using error_reporting(-1), check mysql_error() and then fix that problem.
From now I can see that you've got syntax error in sql query because you're using from as column name which is restricted word. You have to put it in `.
remove the space from top
<?php session_start();
if this didn't work
var_dump($_SESSION) before inserting to check value exist in the session
and use die(mysql_error()); with the query
$result=mysql_query($sql) or die(mysql_error());;
if(isset($_POST['chksbmt']) && !$errors)
{
header("location:booking_detail.php");
}
Above code will be executed once the form is submitted if chksbmt is the name of the submit button.
It takes to that page mentioned in header before inserting.
Write all your stuff in between above curly braces, use
if(isset($_POST['chksbmt']) && !$errors)
{
//all your stuff, ex:storing in DB.
if($result){
header("location:booking_detail.php");
}
}
I hope that I've understood your problem, this will workout.
First remove quotes from all session variables like:
{$_SESSION['source_point']}
Second you're redirecting before mysql_error check, Check on results and error first and then redirect:
if (!$result) {
die(mysql_error());
}
if(isset($_POST['chksbmt']) && !$errors)
{
header("location:booking_detail.php");
}
1) Start session if its separate script.
2) Remove reserved keyword as suggested by #Mihai in your query.
3) In your query It should be VALUES( instead of VALUES.
4) As you are mention in your comment leaving_from not inserting into Db.
Because in your script you have not assign session value for $_SESSION['source_point'] .
In your script will be :-
<?php
session_start();
if (!isset($_SESSION)){
}
$total_amt = $_POST['total_amt'];
$total_seats = $_POST['total_seats'];
$boarding_point = $_POST['boarding_point'];
$_SESSION['total_amt'] = $total_amt;
$_SESSION['total_seats'] = $total_seats;
$_SESSION['boarding_point'] = $boarding_point;
// Set here session value for $_SESSION['source_point'] as well,
There are not really and direct answers on this, so I thought i'd give it a go.
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id = " .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
The above code is supposed to set the variable $myid as the posted content of id, the variable is then used in an SQL WHERE clause to fetch data from a database according to the submitted id. Forgetting the potential SQL injects (I will fix them later) why exactly does this not work?
Okay here is the full code from my test of it:
<?php
//This includes the variables, adjusted within the 'config.php file' and the functions from the 'functions.php' - the config variables are adjusted prior to anything else.
require('configs/config.php');
require('configs/functions.php');
//Check to see if the form has been submited, if it has we continue with the script.
if(isset($_POST['confirmation']) and $_POST['confirmation']=='true')
{
//Slashes are removed, depending on configuration.
if(get_magic_quotes_gpc())
{
$_POST['model'] = stripslashes($_POST['model']);
$_POST['problem'] = stripslashes($_POST['problem']);
$_POST['info'] = stripslashes($_POST['info']);
}
//Create the future ID of the post - obviously this will create and give the id of the post, it is generated in numerical order.
$maxid = mysql_fetch_array(mysql_query('select max(id) as id from repairs'));
$id = intval($maxid['id'])+1;
//Here the variables are protected using PHP and the input fields are also limited, where applicable.
$model = mysql_escape_string(substr($_POST['model'],0,9));
$problem = mysql_escape_string(substr($_POST['problem'],0,255));
$info = mysql_escape_string(substr($_POST['info'],0,6000));
//The post information is submitted into the database, the admin is then forwarded to the page for the new post. Else a warning is displayed and the admin is forwarded back to the new post page.
if(mysql_query("insert into repairs (id, model, problem, info) values ('$_POST[id]', '$_POST[model]', '$_POST[version]', '$_POST[info]')"))
{
?>
<?php
$myid = $_POST['id'];
//Select the post from the database according to the id.
$query = mysql_query("SELECT * FROM repairs WHERE id=" .$myid . " AND name = '' AND email = '' AND address1 = '' AND postcode = '';") or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row = mysql_fetch_array($query))
{
$model = $row['model'];
$problem = $row['problem'];
}
//Select the post from the database according to the id.
$query2 = mysql_query('SELECT * FROM devices WHERE version = "'.$model.'" AND issue = "'.$problem.'";') or die(header('Location: 404.php'));
//This re-directs to an error page the user preventing them from viewing the page if there are no rows with data equal to the query.
if( mysql_num_rows($query2) < 1 )
{
header('Location: 404.php');
exit;
}
//Assign variable names to each column in the database.
while($row2 = mysql_fetch_array($query2))
{
$price = $row2['price'];
$device = $row2['device'];
$image = $row2['image'];
}
?>
<?php echo $id; ?>
<?php echo $model; ?>
<?php echo $problem; ?>
<?php echo $price; ?>
<?php echo $device; ?>
<?php echo $image; ?>
<?
}
else
{
echo '<meta http-equiv="refresh" content="2; URL=iphone.php"><div id="confirms" style="text-align:center;">Oops! An error occurred while submitting the post! Try again…</div></br>';
}
}
?>
What data type is id in your table? You maybe need to surround it in single quotes.
$query = msql_query("SELECT * FROM repairs WHERE id = '$myid' AND...")
Edit: Also you do not need to use concatenation with a double-quoted string.
Check the value of $myid and the entire dynamically created SQL string to make sure it contains what you think it contains.
It's likely that your problem arises from the use of empty-string comparisons for columns that probably contain NULL values. Try name IS NULL and so on for all the empty strings.
The only reason $myid would be empty, is if it's not being sent by the browser. Make sure your form action is set to POST. You can verify there are values in $_POST with the following:
print_r($_POST);
And, echo out your query to make sure it's what you expect it to be. Try running it manually via PHPMyAdmin or MySQL Workbench.
Using $something = mysql_real_escape_string($POST['something']);
Does not only prevent SQL-injection, it also prevents syntax errors due to people entering data like:
name = O'Reilly <<-- query will bomb with an error
memo = Chairman said: "welcome"
etc.
So in order to have a valid and working application it really is indispensible.
The argument of "I'll fix it later" has a few logical flaws:
It is slower to fix stuff later, you will spend more time overall because you need to revisit old code.
You will get unneeded bug reports in testing due to the functional errors mentioned above.
I'll do it later thingies tend to never happen.
Security is not optional, it is essential.
What happens if you get fulled off the project and someone else has to take over, (s)he will not know about your outstanding issues.
If you do something, finish it, don't leave al sorts of issues outstanding.
If I were your boss and did a code review on that code, you would be fired on the spot.
I'm using this php code to update a table, but nothing is updating?
if(isset($Submit))
{
include('connect_mysql.php');
for($i=0;$i<$count;$i++)
{
$sql = "UPDATE $table SET cost='{$cost[$i]}', net=('{$bypiece[$i]}' + '{$cost[$i]}') WHERE serial='{$serial[$i]}'";
$result = mysql_query($dbcon, $sql);
}
}
if($result)
{
header("location:admin-index.php#office.php");
mysql_close();
}
It seems like it should work, and i have no reason why it wouldn't.
My variables are defined, and when i echo them out with an else statement everything seems to be alright. Yet the data isn't being updated, and the header isn't redirecting.
Can anyone help me find a working solution?
A good idea when debugging is turn on error reporting.
error_reporting(E_ALL);
ini_set('display_errors', '1');
Also see if you have any errors in your sql statement by changing
$result=mysql_query($dbcon, $sql);
to
$result=mysql_query($dbcon, $sql) or die(mysql_error());
What is $count set to? Your code would go nowhere in the state that it is in right now since $count isn't set to anything.
Change:
net=('{$bypiece[$i]}' + '{$cost[$i]}')
To:
net=({$bypiece[$i]} + {$cost[$i]})
You should also have some error checking with the query.
if(isset($Submit)){
include('connect_mysql.php');
$count=20;
for($i=0;$i<$count;$i++){
$sql="UPDATE $table SET cost='{$cost[$i]}', net=({$bypiece[$i]} + {$cost[$i]}) WHERE serial='{$serial[$i]}'";
$result=mysql_query($dbcon, $sql) or die(mylsql_error());
}
if($result){
header("location:admin-index.php#office.php");
mysql_close();
}
}
<?php
include 'connect.php';
include 'header.php';
$page = "signup.php";
// receive the invite code:
$code = $_POST['code'];
$sql = "SELECT codes FROM invites WHERE codes='$code'";
// check the table for matching codes
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) {
// end any previously defined sessions.
session_start();session_unset();session_destroy();
// start a new session
session_start();
// define the session variable.
// this allows us to check if it's set later and is required for
// the script to run properly.
$code = $_POST["code"];
mysql_query("DELETE FROM invites WHERE codes='$code'");
header('Location: '.$page);
exit;
} else {
echo "Invite invalid. Please try again later.";
echo $code;
}
include 'footer.php';
?>
I am trying to implement an invite system to a webpage I am working on. However when trying to evaluate if there is a row containing the invite code I keep either getting nothing or this warning. The warning in this case but if I change the if state to ==1, it allows everyone regardless of code and ==0 does throws different errors.
if (mysql_query($result)) {
Try mysql_num_rows there.
There are a few things wrong here.
1) SQL Injection vulnerabilities, don't ever pass a superglobal $_POST or $_GET or any other user-supplied variable directly inside your query!
Use at minimum mysql_real_escape_string() to the variable before letting it into the query, or better look into parametrized queries, it's the best way to avoid SQL vulnerabilities
2)
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) ....
This doesn't check if request returns 1 or 0 rows, you should use mysql_num_rows() here instead
if(mysql_num_rows() == 1) //or whatever you need to check
3)
session_start();session_unset();session_destroy();
// start a new session
session_start();
session_start() should be called before anything in your page. Don't know why this redundancy of calling, unsetting, destroying, recalling it here. If you want another id, just use session_regenerate_id();
And as already said by other, use some error reporting in your query, something like
$result = mysql_query($sql) or die(mysql_error())
to actually see what's failed, where and why.
Problem is your query. First of all check your statement and use this :
$result = mysql_query($sql) or die(mysql_error());
instead of this
$result = mysql_query($sql);
So, you can see are there any error at your SQL query .