Script not populating MySQL database - do I have syntax errors? [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to populate a MySQL database by uploading contents of a SQLite database from my Android application. However when I do so the MYSQL database doesn't get populated.
The PHP script that I am trying to use to populate is as follows (note username, password etc are left out purposely, but are definitely correct). Are there any syntax errors or what could the issues be?
<?php
if(isset($_GET['sessionId']) && isset($_GET['game']) && isset($_GET['name']) && isset($_GET['avgMed']) && isset($_GET['maxMed']) && isset($_GET['avgAttn']) && isset($_GET['maxAttn']) && isset($_GET['score']) && isset($_GET['date'])
&& isset($_GET['rawFile']) && isset($_GET['EEGFile']) && isset($_GET['medFile']) && isset($_GET['attFile']))
{
$mysql_host = "";
$mysql_database = "";
$mysql_user = "";
$mysql_password = "";
// Provide host ip, mysql user name, password
$con = mysql_connect($mysql_host,$mysql_user,$mysql_password);
// Provide database name.
mysql_select_db($mysql_database);
$sessionId=$_GET['sessionId'];
$game=$_GET['game'];
$name=$_GET['name'];
$avgMed=$_GET['avgMed'];
$maxMed=$_GET['maxMed'];
$avgAttn=$_GET['avgAttn'];
$maxAttn=$_GET['maxAttn'];
$score=$_GET['score'];
$date=$_GET['date'];
$rawFile=$_GET['rawFile'];
$EEGFile=$_GET['EEGFile'];
$medFile=$_GET['medFile'];
$attFile=$_GET['attFile'];
$flag="false";
if(!empty($game) && !empty($name) && !empty($date) && !empty($sessionId))
{
$sql="Insert into `GameDetails` (`SessionID`,`Game`,`Username`,`AvgMeditation`,`MaxMeditation',`AvgAttention` ,`MaxAttention`,`Score`,`Date`,`RawFile' ,`EEGFile', `MedFile', `AttFile') values
('$sessionId','$game','$name','$avgMed','$maxMed','$avgAttn','$maxAttn','$score','$date','$rawFile','$EEGFile','$medFile','$attFile') ";
$result=mysql_query($sql);
if($result)
{
$count= mysql_affected_rows();
if($count > 0)
{
$flag="true"; //result true
}
}
mysql_close($con);
echo json_encode(array("result"=>$flag));
}
}
?>
I also recently made a change to the MySQL database within phpMyAdmin and added four new columns but I am sure that they are referenced correctly in the script.

You have multiple typos:
[...snip...],`Date`,`RawFile' ,`EEGFile', `MedFile', `AttFile') values
^----------^----------^----------^--- here
Those should be backticks (`), not ' single quotes.
If you had any kind of error handling in your script, you'd have been told about the syntax errors:
$result=mysql_query($sql) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
and on top of that, you're vulnerable to sql injection attacks, so it's a good thing this query isn't working, since your syntax errors are preventing any injection attack from occurring int he first place.
Never EVER assume success when dealing with external resources, e.g. a database. Always assume failure, and treat success as a pleasant surprise. There's exactly ONE way for a query to succeed, and near infinite number of reasons for them to fail.

Related

My POS application is inserting records twice into the database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
I have been trying to insert into my database but it inserts with a random behavior. Although, the code runs correctly on PHP Version 7., I'm having problems with running it on PHP Version 8.1.2.
Sometimes it inserts correctly, most times it inserts twice. That's my only challenge actually. I also tried to fix by reporting errors using || ob_start(); ini_set('display_errors', 1); || and also disabled the javascript alert but no error was displayed. I'd appreciate it if you could look at the code a little closer. I checked the error logs and there's no problem.
if(isset($_POST['submit_sales'])){
$prd = $_POST['prd'];
$count = count($prd);
$rand_sales = rand();
$cust_name = check_input($_POST['custname']);
$cust_num = check_input($_POST['custnumber']);
// echo $count;
// Looping all files
if($count<1){
// $error = 'Cart is empty';
echo '<script>alert("Cart is empty !!!");window.location="all_products.php";</script>';
// echo '<script>window.location="all_products.php";</script>';
}else{
for($i=0;$i<$count;$i++){
$products = $_POST['prd'][$i];
$price = $_POST['price'][$i];
$qty = $_POST['qty'][$i];
$fl= dbconnect()->prepare("INSERT INTO sales SET cust_name=:custname, cust_number=:custnumber, prd_name=:prd, qty=:qty, price=:price, ref_code=:random");
$fl->bindParam(':custname', $cust_name);
$fl->bindParam(':custnumber', $cust_num);
$fl->bindParam(':prd', $products);
$fl->bindParam(':qty', $qty);
$fl->bindParam(':price', $price);
$fl->bindParam(':random', $rand_sales);
$fl->execute();
}
if($fl){
echo "<script>alert('doneit');window.location='all_products.php';</script>";
}else {
echo "<script>alert('Error Inserting Into Database')</script>";
}
}
}
I had included a script to reload the page in my header hence the double inserting, upon discarding the script, my problem was fixed. Thank you all for helping me with my challenge

can not login to database using php

This is my login php code but I am unable to login.
My code works until echo "2", after that is not working anymore.
include 'inc.config.php';
if(isset($_POST["submit"]))
{
$user = mysql_real_escape_string($_POST['emailid']);
$pass = md5(mysql_real_escape_string($_POST['password']));
$query=mysql_query("SELECT * FROM logsignup WHERE email='$user' AND password='$pass' ");
echo "1";
$numofrows = mysql_num_rows($query);
echo "2";
if($numofrows!=0)
{
echo "3";
while($row=mysql_fetch_assoc($query))
{
$dbusername= $row['emailid'];
$dbpassword= $row['password'];
}
if($user=$dbusername && $pass=$dbpassword)
{
echo "loggedin";
}
}
else
{
echo "invalid";
}
}
Here is inc.config.php file
$con = mysql_connect("localhost","root","");
$select=mysql_select_db("loginsignup");
Image of the database:
Update to MySQLi, as mysql_ is now deprecated. Read How do I migrate my site from mysql to mysqli? as a starter guide.
Stop using md5 as a password hashing function and instead use password_hash or a similar proven function.
if($user=$dbusername && $pass=$dbpassword) this is running the logic:
If value I get out of the database is the same as the value I put into the database.
Which is pretty pointless, it's a needlessly excessive check. It's better to count the correct number of rows returned, which will tell you exactly the same information.
You need to start using error logging, to help yourself solve your own errors, please read How to get useful error messages in PHP?
Also use MySQL EXPLAIN in (PHPMyAdmin) to help you understand wayward SQL queries.
Your password field in your screenshot looks far too short. md5 is typically 32 characters long, so what could be happening is that the SQL comparison is failing because you're comparing a long string with a shorter string. Double check.
Ensure you are using the correct Character encoding throughout your PHP and your MySQL, please read UTF-8 all the way through and convert all MySQL into utf8mb4_unicode_ci. Also get used to using PHP Multibyte string functions (may need installing).
If the above guides do not solve your problem you will at the very least have a clear path (with the error logs) to see what's going wrong and from that how to solve your issue.
<?php
`include 'inc.config.php';
if(isset($_POST["submit"]))
{
$user = mysql_real_escape_string($_POST['emailid']);
$pass = md5(mysql_real_escape_string($_POST['password']));
$sql="SELECT * FROM logsignup WHERE email='$user' AND password='$pass'";
$query=mysql_query($sql);
$numofrows = mysql_num_rows($query);
if($numofrows > 0)
{
$row=mysql_fetch_assoc($query)
$_SESSSION['EMAIL']= $row['emailid'];
$_SESSSION['USERNAME'] $row['username'];
if( $_SESSSION['EMAIL'] && $_SESSSION['EMAIL']) {
echo "valid";
}else{
echo "invalid";
}
}
}`
?>

Why doesn't this work? :/ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I don't understand why this doesn't work? It's a register form checking if fields are filled in,password is equal to retype password, and if it doesn't already exist in database.
I get this error: Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /home/a4550840/public_html/newreg.php on line 32
But I already put a ';' at line 32 ... I don't understand why this error occurs.
Any help is appreciated :).
EDIT: Fixed that error ^ and added the mysql_real_escape_string , but it doesn't register the information to the database for some reason?
EDIT: It works now :), took away the quotations from the query
<?php
include ('connect.php');
if ($_POST['submit']) {
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$repassword = mysql_real_escape_string($_POST['repassword']);
$email = mysql_real_escape_string($_POST['email']);
if ($username && $password && $repassword && $email){
if ($password == $repassword) {
$check = mysql_query("SELECT * FROM members WHERE username='$username' ");
$countrows = mysql_num_rows($check);
if ($countrows == 0){
mysql_query("INSERT INTO members ('username','password','email') VALUES ('$username','$password','$email') ");
} else {
echo 'Username already exists';
}
} else {
echo 'Passwords don'\t match';
}
} else {
echo 'Fill in the fields';
}
} else {
echo 'Register please';
}
?>
You have a problem here:
echo 'Passwords don't match';
You need scape single quote as:
echo 'Passwords don\'t match';
or
echo "Passwords don't match";
NOTE: Your code is vulnerable to sql injection, you should use mysql_real_scape_string() before to pass yours parameters as sql query.
I suggest:
$username = mysql_real_scape_string($_POST['username']);
$password = mysql_real_scape_string($_POST['password']);
$repassword = mysql_real_scape_string($_POST['repassword']);
$email = mysql_real_scape_string($_POST['email']);
TIP: When your are testing (in dev environment) mysql querys, you should combine die(mysql_error()) at the end of line to check if you has a problem like as:
mysql_query('your sql') or die(mysql_error()).
If you have an error, this cause your app die an show the mysql error.
See this reference.
This error shows the earliest time it encounters a problem. The problem is on that line, or on a previous line. In this case you didn't escape a quote, so the parser found the rest of your string while it expected a , or ;. If you look at the colouring of your code, you'll see that more easily. The correct line would be
echo 'Passwords don\'t match';

PHP Form - Check if mysql already contains email data

This register form was made by me, but it doesn't do what I want it to do.
I want it to connect to a mysql database and store the information that was given by the form. I want it to hash the $password in md5 and store it in the "gebruikers" table. Please don't reply with "Damn, you have no idea what you are doing" or something like that. I am learning PHP by looking to examples and following tutorials. Please keep in mind that the mysql insert code is not filled in right, because I got stuck a few lines above.
So, my question is: I want to check if the mysql table already contains $email. If it IS already in the mysql table, I want to display an error message that I can place somewhere else in my PHP page. If the email adress given is unique, than the $password should hash into md5 and store into the mysql database, just like the other form entries.
How do I do that?
<?php
// Fetching all the form details
$email = $_POST["email"];
$password = $_POST["password"];
$voornaam = $_POST["voornaam"];
$tussenvoegsel = $_POST["tussenvoegsel"];
$achternaam = $_POST["achternaam"];
$dag = $_POST["dag"];
$maand = $_POST["maand"];
$jaar = $_POST["voornaam"];
$straat = $_POST["straat"];
$postcode = $_POST["postcode"];
$woonplaats = $_POST["woonplaats"];
$cniveau = $_POST["cniveau"];
$oniveau = $_POST["oniveau"];
$voornaam = $_POST["voornaam"];
$aboutme = $_POST["aboutme"];
//Here's where I don't know how to continue
$check = mysql_query("SELECT * FROM `gebruikers` WHERE `email` = '$email'");
if($check === FALSE) {
//there is a user already registered
echo("$email is al in gebruik. <a href='login.php'>Inloggen</a>?");
} else {
//There isn't a username
//mysql_query("INSERT INTO `user` (`id` ,`username` ,`password`) VALUES (NULL , '{$_POST['email']}', MD5( '{$_POST['password']}' ))");
echo("You have been registered!");
}
P.S.: I'm not a native English speaker, so please ignore my grammar mistakes/typos.
First of all, you made a major mistake: There is a SQL-Injection security hole.
Please read this: http://php.net/manual/en/security.database.sql-injection.php
Second, you should use mysqli instead of mysql, because mysql is deprecated.
Your error is that SQL does only return false if the query is invalid, not if there are no results. So the correct way of checking if there are results is to use http://php.net/manual/en/mysqli-result.num-rows.php
$result = mysql_query("SELECT * FROM `gebruikers` WHERE `email` = '$email' LIMIT 1");
if(mysql_fetch_array($result) !== false)
{
...
} else {
....
}
You should also read up on preventing SQL injection.
Maybe you've forgot to set the mysql_connect statement.
But I strongly recommend you stick from now on, with the mysqli_ functionality, since, as Aragon0 said, mysql is deprecated in PHP's newest versions.
Besides, mysqli statements are simpler than the mysql ones, for example you use one statement (mysqli_connect) to connect to your host and select your database at the same time, instead of using separated statements (both mysql_connect and mysql_select_db).
Oh, and no additional service package is required to use it. :)

Login keeps getting hacked [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I have the below login script which I believe is secure. However, someone keeps getting access to the administration section of the site and changing content.
if(isset($_POST['submit'])) {
$error = false;
$user_login = stripslashes(strip_tags(htmlentities($_POST['user_login'])));
$pass_login = stripslashes(strip_tags(htmlentities($_POST['pass_login'])));
if(!empty($user_login) && !empty($pass_login)) {
$check_details=mysql_query("SELECT * FROM `admin` WHERE email='".$user_login."' AND password='".md5($pass_login)."'");
$status=mysql_num_rows($check_details);
if($status >= "1") {
$error = false;
$_SESSION['wmmadmin_loggedin'] = "1";
$_SESSION['wmmadmin_email'] = "".$user_login."";
header("Location: ./index.php");
}
if(!$status || $status == "0") {
$error = true;
echo "<div id=\"error\"><strong>Error!</strong><br />Login details were incorrect.</div>\n";
}
}
if(empty($user_login) || empty($pass_login)) {
$error = true;
echo "<div id=\"error\"><strong>Error!</strong><br />Enter your username and password.</div>\n";
}
}
At the top of every script there is a function call:
function checkloggedin() {
if($_SESSION['wmmadmin_loggedin'] == "0" || $_SESSION['wmmadmin_loggedin'] !== "1" || $_SESSION['wmmadmin_email'] == "") {
header("Location: login.php");
exit;
}
}
Am I missing something? I need to stop these hackers!
Thanks
Pete
Someone could send the following as user_login:
user_login="nobody' OR 1 OR email='nobody"
This will result in a query
… WHERE email='nobody' OR 1 OR email='nobody' AND password='…'
which is interpreted as
… WHERE email='nobody' OR 1 OR (email='nobody' AND password='…')
so since the middle part is true (1 means true to MySQL), everything is true and access is granted. This is a classical SQL injection attack.
Let's see how you violate the rule of proper escaping for context:
$user_login = stripslashes(strip_tags(htmlentities($_POST['user_login'])));
Assuming the user name DOES contain HTML tags. The <> will first be converted to entities: <>.
Then strip_tags() tries to filter tags - but there are none! Useless function call.
Then you want to remove slashes. Are there any? This function call is only useful if magic quotes are still enabled in your PHP, and you should check if they are, not blindly remove them.
htmlentities() does only convert double quotes to entities, not single quotes. And your SQL uses single quotes to terminate the strings. So the whole bunch of functions used still lets SQL injection through.
Do not invent security functions yourself. Use mysql_real_escape_string() and double quotes in your SQL, and you are save. Or use prepared statements by using mysqli or PDO.
You need to sanitize $user_login and $pass_login more than just checking if they are empty. Someone could pass SQL code in them, and do a sql injection attack.
See here: http://php.net/manual/en/security.database.sql-injection.php

Categories