Failing insert statement in msql - javascript

Below is the section of my code which is causing me problems:
$usertype = $_POST['usertype'];
if ($usertype == "Administration") {
?>
<script type='text/javascript'>
window.onload = promptMessage;
function promptMessage() {
var x = 38773;
var code = prompt('Enter the administration code you have been given:', 'Enter code here');
if (code == x) {
alert("Administration code accepted");
} else {
var secondcode = prompt('The code you have entered is inccorect', 'Enter correct code here or change Usertype');
if (secondcode == x) {
alert("Administration code accepted");
} else {
location.href = 'AdminCodeFail.html';
}
}
}
</script>
<?php
$con = mysqli_connect("localhost:3306", "root", "***********", "systemone");
$sql = "INSERT INTO completeinfo (FirstName, Surname, UniID,
HouseNumber, AddressLineOne, AddressLineTwo, City,
PostCode, County, PhoneNumber, Email, Username,
Password, UserType)
VALUES
('$_POST[firstname]','$_POST[surname]','$_POST[uniid]',
'$_POST[housenumber]','$_POST[addresslineone]',
'$_POST[addresslinetwo]','$_POST[city]','$_POST[postcode]',
'$_POST[county]','$_POST[contactnumber]','$_POST[email]',
'$_POST[username]','$_POST[password]','$_POST[usertype]')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
} else {
header("Location:SignUpComplete.html");
}
The problem I'm having is that the insert query is just not working. The query fails to insert any data into the database and I am at a loss as to why. The connection to the database is working fine and I'm receiving no errors when testing the query itself. So why isn't the query functioning?

Add
error_reporting(E_ALL);
ini_set('display_errors', '1');
after your code and it will give you more descriptive errors as to why the query is failing.

You can't have array variables in double quotes like this:
$string = "hello $array['index'] world!";
They must be:
$string = "hello {$array['index']} world!";
Your code has SQL injection vulnerabilities up the wazoo. I strongly suggest reading: How can I prevent SQL injection in PHP?

How should I write PHP $_POST vars in a mysql_query function?
this is your error and this type of question has already been answered.
use
. mysql_real_escape_string to pop out of the string and recognize a value
LOOK AT THE LINK... it will help :)

Related

Comparing php value with javascript variable?

I am working on php and javascript project. I just want to compare echo return value of php with javascript variable.
php backend code which returns 'no' using echo
if($connection){
$sql ="SELECT secondname FROM account WHERE email = '$email' && password = '$password'";
$searchquery = mysqli_query($connection, $sql);
if(!(mysqli_num_rows($searchquery) == 0)) {
$row = mysqli_fetch_array($searchquery);
$secondname = $row['secondname'];
echo $secondname ;
} else {
echo 'no';
}
Now comparing with javascript variable
$.post("signnin.php",{
email: email,
password: password,
},
function(data, status){
if(data == 'no'){
console.log('same');
}else{
console.log('not same');
}
});
it give same result if value are same or not. i also JSON.stringify but it still not working
The output from the URL probably includes white space.
JSON is a good way to normalize that, but you need to apply it at the PHP end, not the JavaScript end.
$secondname = $row['secondname'];
header("Content-Type: application/json");
echo json_encode([ "secondname" => $secondname ]);
} else {
header("Content-Type: application/json");
echo json_encode([ "failure" => "Login failed" ]);
}
and then:
$.post(
"signnin.php",
{ email, password },
function(data, status){
if(data.failure){
console.log('same');
} else {
console.log('not same');
}
}
);
You are probably sending whitespaces in your PHP script. There are 2 ways to solve this -
Ensure that you put the starting php tag from the very first line and don't put the ending php tag (?>).
Instead of comparing texts, compare numbers. In php script echo 1 and in js compare data==1. This way whitespaces are automatically ignored.

jQuery AJAX check if email exists in database not working for some reason

I am trying to use jQuery, AJAX, PHP, and MySQL to check if an email entered into a form already exists in a database.
This is my current jQuery code :
$.post('check-email.php', {'suEmail' : $suEmail}, function(data) {
if(data=='exists') {
validForm = false;
$suRememberMeCheckbox.css('top', '70px');
$suRememberMeText.css('top', '68px');
$signUpSubmit.css('top', '102px');
$tosppText.css('top', '115px');
$suBox.css('height', '405px');
$suBox.css('top', '36%');
$errorText.text('The email has been taken.');
return false;
};
});
And this is my PHP code:
<?php include("dbconnect.php") ?>
<?php
$sql = "SELECT email FROM users WHERE email = '" .$_POST['suEmail'] . "'";
$select = mysqli_query($connection, $sql);
if (mysqli_num_rows($select) > 0) {
echo "exists";
}
?>
When I go through with the sign up form, when I use an email already in the database, the error text never changes to what I specified, but instead to some other error cases I have coded. Why is this not working! Thanks so much!
You may have extra whitespace in response
Try:
if(data.trim()=='exists') {

Trying to call PHP script from Javascript If statement

I have a form which gets validated by javascript. In one of the if statements, in the final condition (when everything else has been validated) I would like to put my PHP script that updates SQL with one of the passwords.
This is the final validation:
function passwordCheck() {
var password = '<?php echo $password; ?>';
if (document.passwordform.inputedPassword.value == password)
{
if (document.passwordform.Password1.value == document.passwordform.Password2.value)
{
*********************************************************
} else
{
document.getElementById("equalpasswords1").innerHTML = "Passwords should be equal";
document.getElementById("equalpasswords2").innerHTML = "Passwords should be equal";
}
} else
{
text = "Insert a correct password";
document.getElementById("editpassword").innerHTML = text;
}
return true;
}
And I would like to insert a call to my PHP script where the stars are. How could I do this? I read that you can't insert PHP into javascript, so it has to be an external PHP file. My SQL update code is this one:
<?php
$x = $_POST['Password2'];
define('DB_NAME', 'Students');
define('DB_USER', 'Students');
define('DB_PASSWORD', 'Password');
define('DB_HOST','HOST');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use'. DB_NAME. ': ' . mysql_error());
}
$result = "UPDATE `1956218_students`.`Students` SET `Password` = '$x' WHERE `Students`.`StudEmail` = '$email' ";
if (!mysql_query($result)) {
die('error: ' .mysql_error());
}
?>
You need to realize that JavaScript is being executed at client's side (in browser), while the PHP code is being executed at server's side.
So you need to make another request to the server, so that PHP codes can handle / process it (validate the password, prepare some response - ideally in JSON format etc.).
You might want to do something like:
How to validate a username / password via JQuery / Ajax?

How do I insert data from a php file using PDO?

I'm trying to log some data for my website using PDO from a PHP file. I have the following code which is called by by a javascript library, D3. The call works fine, but when I run this code I get an "internal server error".
What am I doing wrong? I have been following a guide on a website and I am basically using the same principles as them. If anyone can help I'd appreciate it. Thanks a lot in advance, my code is pasted below. (Of course the database information is something valid)
$hostname="xxxx";
$username="xxxxxx";
$pw="xxxxxxxx";
$dbname="xxxx";
try {
$pdo = new PDO ("mysql:host=$hostname;dbname=$dbname","$username","$pw");
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
//Gets IP for client.
$ip = get_client_ip();
//An email, format of string.
$email = "test#test.dk";
//An int, in this case 19.
$prgm_name = $_GET["prgm"];
//Piece of text, format of string of course.
$prgm_options.=$prgm_name;
$prgm_options.= " - ";
$prgm_options.=$_GET["gene"];
$prgm_options.=" - ";
$prgm_options.=$_GET["data"];
//Datasize, int.
$data_size = 0;
//Timestamp.
$now = "NOW()";
//Table name.
$STAT_TABLE = "stat";
$query = $pdo->prepare("INSERT INTO $STAT_TABLE (ip, email, prgm, options, datasize, date) VALUES (:ip, :email, :prgm_name, :prgm_options, :data_size, :now);");
$query->execute(array( ':ip'=>'$ip',
':email'=>'$email',
':prgm_name'=>$prgm_name,
':prgm_options'=>'$prgm_options',
':datasize'=>'$datasize',
':now'=>$now));
Try the following Code to Insert
$count = $pdo->exec("INSERT INTO $STAT_TABLE(ip, email, prgm, options, datasize, date) VALUES ('$ip','$email',$prgm_name,'$prgm_options','$datasize',$now)))");
/*** echo the number of affected rows ***/
echo $count;
I like to bind each parameter individually. I think it gives you more control over data types and sizes.
try {
$sth = $pdo->prepare("INSERT INTO...");
$sth->bindParam(":ip", $ip, PDO::PARAM_STR, 16);
$sth->bindParam(":email", $email, PDO::PARAM_STR, 30);
// etc...
$sth->execute();
} catch (Exception $e) {
print_r($e);
}

Check if user exists with AJAX and PHP

I am trying to create a signup form that checks if the user exists in the database, I inserted a sample user and when I tried signing up with that user it didn't say its already been taken. What have I done wrong?
The JavaScript:
function formSubmit()
{
document.getElementById('email_valid').innerHTML = '';
var temail=document.forms["signup_form"]["temail"].value.replace(/^\s+|\s+$/g, '');
var atpos=temail.indexOf("#");
var dotpos=temail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=temail.length)
{
//alert("Not a valid e-mail address");
setTimeout(function(){document.getElementById('email_valid').innerHTML = '<br/>Email must be valid...';},1000);
var temailsub=0;
}
else
{
$.post('/resources/forms/signup/email.php',{email: temail}, function(data){
document.getElementById('email_valid').innetHTML = data;
if(data.exists){
document.getElementById('email_valid').innetHTML = '<br/>The email address you entered is already in use.';
var temailsub=0;
}else{
var temailsub=1;
}
}, 'JSON');
}
if(temailsub==1e)
{
setTimeout(function(){document.getElementById("signup_form").submit();},1000);
}
else
{
return false;
}
}
The PHP file (email.php):
<?php
header('content-type: text/json');
require_once $_SERVER['DOCUMENT_ROOT']."/resources/settings.php";
$query = $pdo->prepare("SELECT * FROM users WHERE email=:email");
$query->execute(array(
":email"=> $_POST['email']
));
echo json_encode(array('exists' => $query->rowCount() > 0));
?>
I have checked and double checked the code, I still cannot see why its not detecting that the email has already been used... what do i need to do to fix this and avoid this in the future?
The problem is that PDOStatement::rowCount() returns the number of rows affected by the last SQL statement. You are performing a SELECT so this value will always be 0. SELECT does not affect any rows. Instead you need to count the number of rows:
$query = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email=:email");
$query->execute(array(
":email"=> $_POST['email']
));
$rows = $query->fetchColumn();
echo json_encode(array('exists' => $rows);
Also from jtheman's comment above, you should replace innetHTML with innerHTML in your JavaScript.

Categories

Resources