The websites not putting the vote on the database - php

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.

Related

PHP Instert will not insert into Database

(so to begin I'm a high school student so not the greatest with the lingo so try your best to guide rather than tell if you can) When using insert to put data into my database from the website it appears to work but nothing appears in the database but no error codes.
I am using Mysqli, PHP, and Wampserver to run a local server and the website will not send data to the Database.
<?php
include 'connect.php';
include 'header.php';
?>
Sign Up<br>
<form method="post" action="">
Username: <input type="text" name="user_name"><br>
password: <input type="password" name="user_pass"><br>
password <Check: input type="password" name="user_pass_check"><br>
Email: <input type="text" name="user_email"><br>
<input type="submit" value="Register">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "INSERT INTO users(user_name, user_pass, user_email) VALUES('".mysqli_real_escape_string($con, $_POST['user_name'])."', '".sha1($_POST['user_pass'])."', '".mysqli_real_escape_string($con, $_POST['user_email'])."', NOW(), 0)";
$result = mysqli_query($con, $sql);
if (!$result) {
echo 'Something went wrong';
echo mysqli_error($con);
} else {
echo "you have successfully registered. you can now <a href='signin.php'>sign in</a> and start posting";
}
}
}
include 'footer.php'?>
In my file used for connection
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'seqevents';
$con = new mysqli($host, $user, $pass, $dbname) or die("cannot connect");
session_start();
if (!isset($_SESSION['user_level'])) {
$_SESSION['user_level'] = 0;
}
I receive no error messages and nothing happens on the website it just reloads and gets rid of any input within the text boxes.
First the (likely) problem, then some other important pointers:
When you insert, you insert set 3 columns (user_name,user_pass,user_email) and then load 5 values into it (NOW() and 0) are extra, it has no clue where to place those values.
DO NOT USE MD5. If you're thinking "yeah, but my site isnt very interesting, why cares" read this line again. DO NOT USE MD5. Or sha1:
Never store passwords in clear text or using MD5/SHA1! Only store password hashes. Use PHP's password_hash() and password_verify() . If you're running a PHP version lower than 5.5 (which I really hope you aren't), you can use the password_compat library to get the same functionality. – Dharman
Use prepared statements. mysqli_real_escape_string is a good first step, but not adequite. Prepared statements secure the query for you. Bit more complex, a lot more secure.
I suggest removing $_SERVER['REQUEST_METHOD'] === 'POST'. What if you have two forms on your page? You're stuck. Instead, give your submit button a name like submitRegForm. Then you can do if( isset($_POST['submitRegForm']) )
DO NOT USE MD5 OR SHA1

Log in cant find error

Hi i am trying to create a very simple log in function using PHP however, after going through the codes, my form seem to be able to perform the function right only when i enter the right user name and password however, if i dont, it doesnt perform its duties here are my codes that i have simplified :
login.php
<form name="userlogin" action="phpprocess/loginprocess.php" method="POST">
<p>Username : <input type="text" id="username" name="username"></p>
<p>Password : <input type="password" id="password" name="password"></p>
<p><input type="submit" id="loginbtn" value="login" ></p>
</form>
loginproccess.php
include "mysqli.connect.php";
$username = $mysqli->real_escape_string($_REQUEST["username"]);
$password = $mysqli->real_escape_string($_REQUEST["password"]);
echo "$username";
echo "$password";
$sql = "select * from users.userlogin where username ='".$username."' and
password = '".$password."'";
$result = $mysqli->query($sql);
if($result == null){
echo"null";
}
if($mysqli -> errno){
error_log($mysqli -> error);
echo $mysqli -> error;
echo " hello";
exit();
}else{
while( list($index, $user1, $pass1) = $result -> fetch_array()){
if($user1 != null && $pass1 != null){
echo "$index $user1, $pass1";
}
}
}
$mysqli->close();
mysqli.connect.php
$host="localhost";
$user="root";
$password="";
$database="users";
$mysqli = new mysqli($host, $user, $password, $database);
if ($mysqli->errno) {
echo "Unable to connect to the database: <br />".$mysqli->error;
exit();
}
what happens is if i enter the wrong user name and password i need the webpage to echo hello , if i enter it right i need it to echo the right user and pass but when enter wrongly, $result does not seem to be null as null and hello is not being printed out. My error log does not display anything. Hope to hear your advice! Thank you in advance !
You print hello when the query gets an error, but it's not an error if the WHERE conditions don't match any rows. It just returns an empty result set. You should use:
if ($result->num_rows == 0) {
echo "hello";
exit();
}
Also, $result->fetch_array() returns an array with both numbered and named indexes. If your table has 3 columns, this will return an array with 6 elements, but you're only assigning to 3 variables.
Use $result->fetch_row() to get an array with just the numbered elements. Also, you shouldn't use SELECT * if you're relying on the order of elements like this, since that depends on the order that the columns were assigned in the CREATE TABLE statement, and this might change if you update your schema. You should list the specific columns you need in the SELECT list.

sql query fails every time

<html>
<head>
</head>
<body>
<form action="login_process.php" method="post">
SID: <input type="text" name="sid">
<br />
Password: <input type="text" name="pw">
<br />
<input type="submit" value="Login">
</form>
</body>
</html>
login_process.php FILE
<html>
<head>
</head>
<body>
<?php
include ("connection.php");
$sid = $_POST['sid'];
$pw = $_POST['pw'];
setcookie("username", "$sid". time()+86400);
$result = mysqli_query($con, "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'") or die('Query failed');
if(!$result){
echo "Failed";
} else {
echo "success". $_COOKIE['username'];
$_SESSION['username'] = $sid;
}
?>
</body>
</html>
I have data in my student_table. But no matter what input i give it says success. even if i click login button without any input it still says success. please help.
You should use quotes when you assign values in sql queries .
SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'
Also look forward Prepared Statements to protect yourself from sql injections.You should also add the code below to fetch selected row :
while ($row = mysqli_fetch_array($result)) {
$_SESSION['username'] = $row['SID'];
}
Start learning basic debugging:
When a query fails bad, just do this:
Instead of running it (mysql_query, or mysqli_query or whatever you have), ECHO it:
echo "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'";
After you submit the form, you will be shown the query that runs, go to phpmyadmin or whatever you use and run the query manually. See if there are errors and also see easier what's going on. Advisable when you do work like this, FIRST try the queries in phpmyadmin then apply them in the code, after you are confident they are ok.
This is not really an answer but more about how to find out what is going wrong when you code does not work as you expect.
First, always put you SQL into a variable by itself. Why, so you can 'var_dump' it and see what is happening. So, try this:
$sql = "SELECT SID FROM student_table WHERE SID=$sid and password=$pw";
var_dump($sql, 'my_query'); // you will see what PHP created.
then try the answer provided:
$sql = "SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'";
At least you will see what is likely to be incorrect.
var_dump($sql, 'the answer_query'); // you will see what PHP created.
$result = mysqli_query($con, $sql) or die('Query failed');
The outer quote marks must be " (double quote) not " ' " (single quote) both of which are perfectly valid PHP. the former allows variables to be replaced in strings.
The latter will treat eveything as a literal string.

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.

what is the equivalent of ispostback(.NET) in 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 (').

Categories