what is the equivalent of ispostback(.NET) in PHP? - php

I just start coding in PHP,
i wrote my first php + mysql program for inserting data through web form. it works fine, but whenever i refresh the page, it automatically saves null record to my database.
i know the solution in .NET is ispostback, but not in php?
can somebody give me some idea in PHP.
Code is here:
<body>
<form action="mySQLTest.php" method="post">
First Name :<input type="text" name ="txtFirstName"/> <br/>
Last Name: <input type="text" name ="txtLastName"/> <br/>
Age : <input type="text" name= "txtAge" /> <br/>
<input type="submit"/>
</form>
<?php
$con = mysql_connect("localhost","root","");
if(!$con)
{
die('Could not Connect:' .mysql_error());
}
mysql_select_db("test", $con);
if($_REQUEST[])
{
$sql1 = "Insert into info(FirstName, LastName, Age) Values('$_POST[txtFirstName]','$_POST[txtLastName]','$_POST[txtAge]')";
}
if(!mysql_query($sql1, $con))
{
die('Error: '.mysql_error());
}
else
{
echo "1 Record Added";
}
mysql_close($con)
?>
</body>

Have you tried if ($_SERVER['REQUEST_METHOD']=='POST')
updated answer:
if ($_SERVER['REQUEST_METHOD']=='POST') {
[insert...]
header('Location: added_record.php');
}

When you use the POST-method, it's better (imho) to use $_POST rather than $_REQUEST. To check whether you have data, you could use isset($_POST['txtFirstName']);. If you need all data, it's best to do this for all input fields, resulting in
if(isset($_POST['txtFirstName']) && isset($_POST['txtLastName']) && isset($_POST['txtAge'])) {
// do stuff
}
If you want to know if there was any field submitted using post, you could use if(!empty($_POST)) {.
On a side note: I know you are just starting PHP, it could be quite dangerous to use user-generated code in queries. When you are building stuff online, for everyone to reach, please read a bit about SQL injection. This will also prevent your code from breaking when someone enters an apostrophe (').

Related

Empty rows created by refreshing page

I've searched on the Internet to get my answer, but I couldn't find a helpful one. I've got a page called 'post.php' with a form where I can add an image and submit it to the database.
The big problem is when I go to mysite.com/post.php a new empty row is created automatically in the database, which I clearly don't want. I want only to update the database after clicking on the submit button my code:
the part of INSERT:
<?php
// POST.PHP POSTING NEW CONTENT
include 'config.php';
// values from form
$id=$_POST['id'];
$title=$_POST['title'];
$pic=$_POST['pic'];
$youtube=$_POST['youtube'];
$cat=$_POST['cat'];
// insert data to mysql
$sql = "INSERT INTO post(id, title, pic, youtube, cat)VALUES('$id', '$title', '$pic', '$youtube', '$cat')";
$result=mysql_query($sql);
// succes added
if(!$result){
echo "Something went wrong!";
}
else {
echo "Yeah, buddy! Your content is added.";
}
// end of post script ^^
?>
// end of insert
//POST IMAGE PAGE
if(isset($_GET['pic'])) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
title: <input name="title" type="text" id="title"><br />
Add url of image;<br />
<input type="text" name="pic" id="pic"/><br />
<?php
echo '
Category game:
<select name="cat"> ';
$query2 = mysql_query("SELECT * FROM `category`");
while($row=mysql_fetch_array($query2)){
echo '
<option value="'.$row["nameID"].'">'.$row["name"].'</option> ';
}
?>
</select>
<input type="submit" onclick="this.disabled = true" name="submit" value="submit">
</form>
<?php
// end script of posting picture
}
?>
You need to add some conditional code around the part that inserts into the database, checking for if any values has been received (if($myvar){ // do stuff }).
Add the rest of your code, specifically the part that adds stuff to the database as that is what's causing you problems, not the code you posted.
You need to wrap the whole block of database insertion code in an if statement. That way, it will not execute until the form has been submitted and $_POST['submit'] has a value:
include 'config.php';
if (isset($_POST['submit'])){
// values from form
$id=$_POST['id'];
// etc... code stays the same down to:
echo "Yeah, buddy! Your content is added.";
}
}//end if (don't forget to add this last bracket)
Also, you should switch to mysqli or PDO, and use parameterized queries. Otherwise, your site is open to a variety of gnarly attacks via SQL injection. It's not that hard to switch, and very, very important.
Check if the post have been set on the file that handles the database input.
if(isset($_POST['pic'])){
//do something
}
else{ // handle the exeption}
Also, you should not use mysql_* functions anymore. they are unsafe and deprecated as-of php 5.5

MySQL check row

So I am messing around with PHP and MySQL, I currently have a database with:
id | username | password
within it, I was wondering if there would be a way of checking if the username entered is the same as the password on the same row/ID (the ID is auto incrementing)
<form action="login.php" method="get">
login >
<input name="log_username" type="text" />
<input name="log_password" type="password" />
<input id="submit" type="submit" />
</form>
I know its possible, but I - myself as a rookie with SQL and PHP cannot figure out ^^'
Thanks in Advance
EDIT:
For those interested this is my current register code (works brilliantly)
<?php
$con=mysqli_connect(###########);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO users (username, password)
VALUES ('$_POST[reg_username]','$_POST[reg_password]')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
SELECT * FROM users WHERE username = :username AND password = :password
Where password is the encrypted version of the password they submitted, because you're totally going to re-write this to encrypt passwords, and use prepared statements to remove your SQL injection vulnerability.
Creating a user login system is such a common thing that there are literally thousands of tutorials you could find on this topic, I suggest you do some basic research.
if ((isset($_GET['log_username']) && $_GET['log_username'] != "") && (isset($_GET['log_password']) && $_GET['log_password'] != "")
{
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$query = "SELECT * FROM users WHERE username = " . $_GET['log_username'] . " AND password = " . $_GET['log_password'];
$result = mysql_query($query);
if (mysql_num_rows($result) < 1)
echo("No record found");
}
This is the simplest way, but I suggest you to use PDO because mysql_query is deprecated.
Although you have requested a PHP solution, in real-world terms this might be better solved with some javascript/jQuery, because presenting the error to the user will not require a page refresh. For your peace of mind, this is what it would look like:
jsFiddle Demo
HTML:
<form id="myForm" action="login.php" method="get">
login >
<input id="log_username" name="log_username" type="text" />
<input id="log_password" name="log_password" type="password" />
<input id="mySubmit" type="submit" />
</form>
jQuery:
$('#mySubmit').click(function(e) {
e.preventDefault();
var un = $('#log_username').val();
var pw = $('#log_password').val();
if ( un == pw ) {
alert('Sorry, username/password cannot be identical');
}else{
$('#myForm').submit();
}
});
Notes:
The above code uses jQuery, so you must reference the jQuery library, usually in the <head> tags, like this:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
Note the use of e.preventDefault, which means: Don't do what a submit button would normally do (in other words, don't submit). We control the submission ourselves, manually.
This is how we use javascript/jQuery to manually submit: $('#myForm').submit();
Note that ID attributes were added to all elements that I needed to reference. Although it is possible to format jQuery to reference elements with or without IDs, this makes it much easier and there is no downside to doing so (although you must follow the rule that all elements must use unique IDs)
Also note that one should not use the word submit for an ID name for a submit button. Doing so may cause problems later.

The websites not putting the vote on the database

So the vote page is at Click here
the Username should go into the text box, and after you vote on both servers, it should send the Username to the database.
<form name="vote" class="short style" method="post" target="_blank">
<input name="username" type="text" size="30" maxlength="30" placeholder="Username"><button id="nextbutton" type="button" onClick="next();">Next</button>
<div style="display: none;" id="button" class="button"><button type="submit" onClick="changeAction('http://www.rune-server.org/toplist.php?do=vote&sid=8289&name=');")>Rune-Server</button><button type="submit" onClick="changeAction('http://www.runelocus.com/toplist/index.php?action=vote&id=30838&id2=');")>RuneLocus</button></div>
</form><br>
im not sure what to add, i think i need to do something with the next button.. but please help! another thing is its a html... should it be php?
but the mysql is working fine and is sending to the client.
its just getting the username to be sent to the database,
heres check vote
if (!$con) {
die("Could not connect to database: " . mysql_error());
}
mysql_select_db("a5999082_oxidepk", $con);
$username = mysql_escape_string($_GET['username']);
if (isset($_GET['username'])) {
$result = mysql_query("SELECT * FROM `votes` where username = '$username'") or die(mysql_error());
$row = mysql_fetch_array($result);
if($row['username'] == $username) {
mysql_query("DELETE FROM `votes` where username = '$username'");
echo "true";
} else {
echo "false";
}
}
mysql_close($con);
and then heres the Call back
<?php
$rspscoding = gethostbyname("http://www.oxidepkz.net63.net");
if($_SERVER['REMOTE_ADDR'] == $rspscoding) {
$con = mysql_connect("mysql1.000webhost.com", "a5999082_oxidepk", "password");
if (!$con) {
die("Could not connect to database: " . mysql_error());
}
mysql_select_db("a5999082_oxidepk", $con);
$username = mysql_escape_string($_GET['username']);
if (isset($_GET['username'])) {
mysql_query("INSERT INTO `votes` (username) VALUES ('$username')") or die(mysql_error());
}
mysql_close($con);
}
?>
also not sure what gethostbyname should be... thanks!
So... several comments
First, you're not sanitizing your data, which leaves you open to SQL injection.
Second, you posted your database credentials in your code example. Anyone reading this can see them and access your database. Editing won't fix that (will still be in history) so I would HIGHLY recommend you change your database credentials. Next time you might want to remove those before posting.
Third, you need to stop using mysql and switch to mysqli
Why shouldn't I use mysql_* functions in PHP?
Fourth, you're using (in a confusing way)
$rspscoding = gethostbyname("http://www.oxidepkz.net63.net");
if($_SERVER['REMOTE_ADDR'] == $rspscoding) { }
That will never succeed because $_SERVER['REMOTE_ADDR'] contains the IP of the user, not the host name (and your user won't be posting from your server either, which is what I assume $rspscoding is). Check out the PHP $_SERVER reference.

HTML form will not submit

This is my form
<html>
<head><title>Hawkins Car Records</title></head>
<body><h1>Add New Car</h1></body>
<form action="carNewBack.php" method="POST">
Car Name: <input type="text" name="carName"/>
<br>
Make: <input type="text" name="make"/>
<br>
Model: <input type="text" name="model"/>
<br>
Year: <input type="text" name="year"/>
<br>
Last 5 digits of VIN: <input type="text" name="lastVIN"/>
<br>
Plate: <input type="text" name="plate"/>
<br><br>
<input type="submit" value="Submit"/>
</form>
</html>
When I hit the submit button, nothing happens. No white screen, no 404, nothing. It doesn not execute carNewBack.php. Can someone share any ideas?
Here is the action file. Im trying to build a data base of service records of my family's cars and this is the form that takes input and creates a new car record.
<?php
$carconnect = mysqli_connect("localhost", "carUser", "caps271:snows", "cars");
if (mysqli_connect_errno()) {
printf("connect failed: %s\n", mysqli_connect_error());
exit();
} else {
$carName = mysqli_real_escape_string($_POST['carName']);
$make = mysqli_real_escape_string($_POST['make']);
$model = mysqli_real_escape_string($_POST['model']);
$year = mysqli_real_escape_string($_POST['year']);
$lastVIN = mysqli_real_escape_string($_POST['lastVIN']);
$plate = mysqli_real_escaped_string($_POST['plate']);
$sql = "INSERT INTO cars (carName, make, model, year, lastVIN, plate) VALUES ('". $carName."', '".$make."', '".$model."', '".$year."', '".$lastVIN."', '". $plate."')";
$res = mysqli_query($carconnect, $sql);
if ($res === TRUE) {
echo "Car added";
} else {
printf ("Could not insert car: %s\n", mysqli_error($carconnect));
}
mysqli_close($carconnect);
}
?>
Edit: Code fixes.
your <body> tag is closed too early (on line 3), you should close it right before </html> so on line 18
Dear brother its simple..
check out your header there must be something like:
error_reporting(0); or something like that in your php.ini file to Suppress the errors.
2.There is no valid default function as mysqli_real_escaped_string(); unless you have it user defined.
It is mysqli_real_escape_string();
kindly have a look at mysqli_real_escape_string()
hope it was helpful :)
if carNewBack.php is not printing anything back to the screen or redirecting the page. What are using to host the website? If you do not have a web service that does not have php support then this could be an issue.
The form you submitted looks correct (http://www.w3schools.com/php/php_forms.asp), I imagine the real issue could lie in the php handler. If you do not get an error, that means that it does find the php handler.
I also tested your code and it looks fine, so another option could be the browser you are using or even the zoom (I use Google Chrome).

Insert Into - php mysql

HTML
<form action="inc/q/prof.php?pID=<?php echo $the_pID; ?>" method="post">
<select id="courseInfoDD" name="courseInfoDD" tabindex="1"><?php while($row3 = $sth3->fetch(PDO::FETCH_ASSOC)) {
echo "<option>".$row3['prefix']." ".$row3['code']."</option>"; }echo "</select>"; ?>
<input type="text" id="addComment" name="addComment" tabindex="3" value="Enter comment" />
<input type="hidden" name="pID" value="<?php echo $the_pID; ?>">
<input type="submit" name="submit" id="submit" />
</form>
PHP
$connect = mysql_connect("##", $username, $password) or die ("Error , check your server connection.");
mysql_select_db("###");
//Get data in local variable
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
if(!empty($_POST['addComment']))
$course_info=mysql_real_escape_string($_POST['addComment']);
if(!empty($_POST['pID']))
$the_pID=mysql_real_escape_string($_POST['pID']);
print_r($_POST);
echo $the_pID;
// check for null values
if (isset($_POST['submit'])) {
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
else if(!isset($_POST['submit'])){echo "No blank entries";}
else{echo "Error!";}
?>
?>
Table
commId int(11)
info text
date timestamp
reported char(1)
degree char(1)
pID int(11)
cID int(11)
It gives me "Error!" now, I try the db credentials and they are fine... ?? And the r_post() is still giving an error of Array()
Why isn't Array() accepting values? Anyone???
Like #user551841 said, you will want to limit your possibility of sql injection with his code.
You are seeing that error because you're code told it to echo that error if nothing was entered, which is the case upon first page load. You shouldn't need that until submit is done.
Edit: Sorry, I was assuming you are directly entering the page which needs the $_POST data without going through the form submit.
You also should do something along the lines of if(!isset($variable)) before trying to assign it to something less your server will spit out error of undefined variables.
if(!empty($_POST['courseInfoDD']))
$course_info=mysql_real_escape_string($_POST['courseInfoDD']);
do that to all of them.
Then you can check
if (!isset($user_submitted) && !isset($the_comment) && !isset($course_info) && !isset($the_pID) ){
echo "All fields must be entered, hit back button and re-enter information";
}
else{
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
mysql_query($query) or die(mysql_error());
echo "Your message has been received";
}
Check that the hidden field "pID" has a value set from value=<?php echo $the_pID; ?>
Make sure that your data is valid before checking it.
For instance do
print_r($_POST);
and check if the keys and their data match up.
Also, as a side note, NEVER do what you're doing with :
$query="INSERT INTO Comment (info, pID, cID) values('$the_comment','$the_pID','$course_info')";
This is how mysql injection happens, either use prepared statements or
$course_info= mysql_real_escape_string($_POST['courseInfoDD']);
To answer to your question what is wrong here
you've got a huge gaping SQL-injection hole!!
Change this code
//Get data in local variable
$course_info=$_POST['courseInfoDD'];
$the_comment=$_POST['addComment'];
$the_pID=$_POST['pID'];
To this
//Get data in local variable
$course_info = mysql_real_escape_string($_POST['courseInfoDD']);
$the_comment = mysql_real_escape_string($_POST['addComment']);
$the_pID = mysql_real_escape_string($_POST['pID']);
See: How does the SQL injection from the "Bobby Tables" XKCD comic work?
For more info on SQL-injection.
i would change this line
if (isset($_POST['submit'])) {
to
if ($_POST) {
the sumbit button field will not always be posted, for example if you press return on keyboard instead of clicking on the submit button with the mouse.
Cleaner:
$submit = isset($_POST['submit']) ? true : false;
$comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';
if ($submit && $comment) {
$query = 'INSERT INTO comments (comment) values("' . mysql_real_escape_string($comment) . '")';
//...
}
As you can see I place the escaping inside the query. And this is a good idea because sometimes you loose track of the complete code and this won't happen inside a query.

Categories