Can I fetch any variable (eg: username) from another script? Suppose there is a id which is in another table and I want to use as the 'id' field as foreign key in the new table. So how can I fetch it?
<?php
$submit=$_POST['submit'];
include_once('connection.php');
include_once('Home.php');
//Form Data
$id=mysql_query("SELECT id from users WHERE username='$username' ");
$pickup=strip_tags($_POST['pickup']);
$drop=strip_tags($_POST['drop']);
$time=strip_tags($_POST['time']);
$date=date("Y-m-d");
//$orderid =strip_tags($_POST['orderid']);
if($submit)
{ //check for existance
if($pickup && $drop && $time)
{
$queryreg = mysql_query("INSERT INTO ambu_book VALUES ('','$pickup','$drop','$time','$date','')");
}
else
{
echo "Please fill in all fields ! <p>";
}
}?>
Yes, you can use a variable from another php script if you do require() or include the script in the invocking script. But for how you did you wrote your question it seems you have an issue related to sql rather than php, i think.
Related
This system is based on invitation codes, if u have a code that is present in the database you can submit the input therefore change a value in a row. There are 2 inputs, 1) Invitation Code (key), if exist in the database the user can submit the value 2)Name (user). I done the following code but it doesn't work, any suggestions?
<?php
//get value pass from form in login.php
$username = $POST['user'];
$password = $POST['key'];
//connect to the server and select database
mysql_connect("localhost", "...","...");
mysql_select_db("...");
// Query the database for user
$result = mysql_query("UPDATE invitation_keys SET name ='$username' WHERE key = '$password'";)
or die("Failed to query database".mysql_error());
$row = mysql_fetch_array($result);
if ($row['key'] == $password) {
echo "Login success!!!".$row['key'];
} else {
echo "Failed to login";
}
?>
When you are coding in PHP, var_dump($var) is your best friend.
So the first thing to do here, is to print the query.
You will see, that your $username and $password vars are NULL, because you missed the syntax of $_POST[].
After, you can put in var_dump what you want, and that's why its interesting, because you will debug faster with this.
Please could someone give me some much needed direction...
I have a registration form, however I need to add a condition that if the username is already in the table, then a message will appear. I have a had a few goes except it just keeps adding to the SQL table.
Any help would be much appreciated. Here is my current code:
Thanks in advance!
<?php
session_start();session_destroy();
session_start();
$regname = $_GET['regname'];
$passord = $_GET['password'];
if($_GET["regname"] && $_GET["regemail"] && $_GET["regpass1"] && $_GET["regpass2"] )
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$host="localhost";
$username="xxx";
$password="xxx";
$conn= mysql_connect($host,$username,$password)or die(mysql_error());
mysql_select_db("xxx",$conn);
$sql="insert into users (name,email,password) values('$_GET[regname]','$_GET[regemail]','$_GET[regpass1]')";
$result=mysql_query($sql,$conn) or die(mysql_error());
print "<h1>you have registered sucessfully</h1>";
print "<a href='login_index.php'>go to login page</a>";
}
else print "passwords don't match";
}
else print"invaild input data";
?>
User kingkero offered a good approach. You could modify your table so that the username field is UNIQUE and therefore the table cannot contain rows with duplicate usernames.
However, if you cannot modify the table or for other reasons want to choose a different approach, you can first try to run a select on the table, check the results and act accordingly:
$result=mysql_query('SELECT name FROM users WHERE name="'.$_GET['regname'].'"');
$row = mysql_fetch_row($result);
You can then check $row if it contains the username:
if($row['name']==$_GET['regname'])
If this statement returns true, then you can show the user a message and tell him to pick a different username.
Please note
Using variables that come directly from the client (or browser) such as what might be stored in $_GET['regname'] and using them to build your SQL statement is considered unsafe (see the Wikipedia article on SQL-Injections).
You can use
$regname=mysql_escape_string($_GET['regname'])
to make sure that its safe.
Firstly, there is some chaos on the second line:
session_start();session_destroy();
session_start();
Why you doing it? Just one session_start(); needed.
Then you can find users by simple SQL query:
$sql="SELECT * FROM users WHERE name = '$regname'";
$result=mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
//...echo your message here
}
When you got it, I suggest you to rewrite your code with use of PDO and param data binding, in order to prevent SQL injections and using of obsolete functions.
<?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,
I have am creating a Website that showes Visitors Info. Users are able to visit the page and use Textarea to pick a name for their URL, and the name will be saved as a table in mysql database..
I am using the $name variable in my first php file which is a replacement for the text "visitor_tracking". But today I noticed that there is also another php file and more sql codes, and once again I can see that this file also has the "visitor_tracking" text used in the sql code.
But I think I failed big time, because I simply dont know how to replace the "visitor_tracking" text with my the variable name called $name.
<?php
//define our "maximum idle period" to be 30 minutes
$mins = 30;
//set the time limit before a session expires
ini_set ("session.gc_maxlifetime", $mins * 60);
session_start();
$ip_address = $_SERVER["REMOTE_ADDR"];
$page_name = $_SERVER["SCRIPT_NAME"];
$query_string = $_SERVER["QUERY_STRING"];
$current_page = $page_name."?".$query_string;
//connect to the database using your database settings
include("db_connect.php");
if(isset($_SESSION["tracking"])){
//update the visitor log in the database, based on the current visitor
//id held in $_SESSION["visitor_id"]
$visitor_id = isset($_SESSION["visitor_id"])?$_SESSION["visitor_id"]:0;
if($_SESSION["current_page"] != $current_page)
{
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string, visitor_id)
VALUES ('$ip_address', '$page_name', '$query_string', '$visitor_id')";
if(!mysql_query($sql)){
echo "Failed to update visitor log";
}
$_SESSION["current_page"] = $current_page;
}
} else {
//set a session variable so we know that this visitor is being tracked
//insert a new row into the database for this person
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string)
VALUES ('$ip_address', '$page_name', '$query_string')";
if(!mysql_query($sql)){
echo "Failed to add new visitor into tracking log";
$_SESSION["tracking"] = false;
} else {
//find the next available visitor_id for the database
//to assign to this person
$_SESSION["tracking"] = true;
$entry_id = mysql_insert_id();
$lowest_sql = mysql_query("SELECT MAX(visitor_id) as next FROM visitor_tracking");
$lowest_row = mysql_fetch_array($lowest_sql);
$lowest = $lowest_row["next"];
if(!isset($lowest))
$lowest = 1;
else
$lowest++;
//update the visitor entry with the new visitor id
//Note, that we do it in this way to prevent a "race condition"
mysql_query("UPDATE visitor_tracking SET visitor_id = '$lowest' WHERE entry_id = '$entry_id'");
//place the current visitor_id into the session so we can use it on
//subsequent visits to track this person
$_SESSION["visitor_id"] = $lowest;
//save the current page to session so we don't track if someone just refreshes the page
$_SESSION["current_page"] = $current_page;
}
}
Here is a very short part of the script:
I really hope I can get some help to replace the "visitor_tracking" text with the Variable $name...I tried to replace the text with '$name' and used also different qoutes, but didnt work for me...
And this is the call that I used in my 2nd php file that reads from my first php file:
include 'myfile1.php';
echo $var;
But dont know if thats correct too. I cant wait to hear what I am doing wrong.
Thank you very much in advance
PS Many thanks to Prix for helping me with the first php file!
first you need to start session in both pages. it should be the first thing you do in page before writing anything to page output buffer.
In first page you need to assign the value to a session variable. if you don't start session with session_start you don't have a session and value in $_SESSION will not be available.
<?php
session_start(); // first thing in page
?>
<form action="" method="post" >
...
<td><input type="text" name="gname" id="text" value=""></td>
...
</form>
<?PHP
if (isset($_POST['submit'])) {
$name = $_POST['gname'];
//...
//Connect to database and create table
//...
$_SESSION['gname'] = $name;
...
// REMOVE THIS Duplicate -> mysql_query($sql,$conn);
}
?>
in second page again you need to start session first. Before reading a $_SESSION variable you need to check if it has a value (avoid errors or warnings). next read the value and do whatever you want to do with it.
<?php
session_start(); // first thing in page
...
if(isset($_SESSION['gname'])){
// Read the variable from session
$SomeVar = $_SESSION['gname'];
// Do whatever you want with this value
}
?>
By the way,
In your second page, I couldn't find the variable $name.
The way you are creating your table has serious security issue and least of your problems will be a bad table name which cannot be created. read about SQL injection if you are interested to know why.
in your first page you are running $SQL command twice and it will try to create table again which will fail.
Your if statement is finishing before creating table. What if the form wasn't submitted or it $_POST['gname'] was emptY?
there are so many errors in your second page too.
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.