MYSQL Tables Picky About Fields? - php

I am having issues with php and mysql once again. I have a database setup with the table users and I want to make a SELECT COUNT(*) FROM users WHERE {value1} {value2} etc...but the problem is that the 3 fields I want to compare are not in order in the table and when trying the SELECT query, the result vairable($result) is NOT returned properly(!$result). Is there a way to check multiple fields in a mysql table that have fields in between them? Here is an example of what I want to accomplish:
A mysql table called users contains these fields: a,b,c,d,e,f,g,h,i,j,k,l and m.
I want to make a SELECT COUNT(*) FROMusersWHERE a='$_SESSION[user]' and d='$_SESSION[actcode]' and j='$_SESSION[email]' but the statement in quotes is my query and it always executes the if (!$result) { error("An error has occurred in processing your request.");} statement. What am I doing wrong? On the contrary, whenever I try the statement using only one field, ex a, the code works fine! This is an annoying problem that I cannot seem to solve! I have posted the code below, also note that the error function is a custom function I made and is working perfectly normal.
<?php
include "includefunctions.php";
$result = dbConnect("program");
if (!$result){
error("The database is unable to process your request at this time. Please try again later.");
} else {
ob_start();
session_start();
if (empty($_SESSION['user']) or empty($_SESSION['password']) or empty($_SESSION['activationcode']) or empty($_SESSION['email'])){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} elseif ($_SESSION['password'] != "password"){
error("This information is either corrupted or was not submited through the proper protocol. Please check the link and try again!");
} else {
$sql = "SELECT * FROM `users` WHERE `username`='$_SESSION[user]' and `activationcode`='$_SESSION[activationcode]' and `email`='$_SESSION[email]'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql);
if (!$result) {
error("A database error has occurred in processing your request. Please try again in a few moments.");/*THIS IS THE ERROR THAT WONT GO AWAY!*/
} elseif (mysql_result($result,0,0)==1){/*MUST EQUAL 1 OR ACCOUNT IS INVALID!*/
echo "Acount activated!";
} else {
error("Account not activated.");
}
}
}
ob_end_flush();
session_destroy();
?>

Try enclosing your $_SESSION variables in curly brackets {} and add or die(mysql_error()) to the end of your query -
$sql = "SELECT * FROM `users` WHERE `username`='{$_SESSION['user']}' and `activationcode`='{$_SESSION['activationcode']}' and `email`='{$_SESSION['email']}'";/*DOES NOT MATTER WHAT ORDER THESE ARE IN, IT STILL DOES NOT WORK!*/
$result = mysql_query($sql) or die(mysql_error());

store your session value in another varibles then make query , i think
it's work proper
$usr=$_SESSION['user'];
$acod=$_SESSION['activationcode'];
$eml=$_SESSION['email'];
$sql = "SELECT * FROM `users` WHERE `username`='$usr' and `activationcode`='$acod' and `email`='$eml'";
$result = mysql_query($sql) or die(mysql_error());

Related

Check if username already exists in database

I'd like to make an if statement that checks if the username, already exists in the MYSQL database. I tried some different stuff, but i cant make it work. Every time I test it in my browser I get a notice
Notice: Undefined index: username in etc.
I am confused if it has anything to do with the $result variable or the $check variable or neither.
Here is the HTML form and the PHP script.
https://gist.github.com/anonymous/9704354
Thank you and have a nice weekend!
There are a few things that are wrong in your code.
First, never place variables directly in SQL queries, thats how SQL injections happen. Start using PDO or another library for your MYSQL.
The reason you are getting an undefined notice is because of this line.
$result = mysql_query("SELECT * FROM users WHERE username = '$_POST[create_user]'");
It should be this without fixing the huge SQL Injection flaw
$result = mysql_query("SELECT * FROM users WHERE username = '{$_POST['create_user']}'");
Also you should add a "LIMIT 1" to the end of the select query to speed things up. No need looking for more than one user.
You can verify the user by just checking for row_count instead of checking the text values. Since MySQL is not case sensitive for some fields, username "AAAaaa" will be equal to "aaaAAA". If you check row count instead, you will be sure that no usernames are in the database of that text. Or if you want to check using PHP, make sure you pass the usernames through strtolower()
When you start using PDO, the following example will help you.
$dbh = new PDO() // Set the proper variables http://us2.php.net/pdo
if(empty($_POST['create_user'])) {
echo 'Username is Empty. Always check if POST and Get data is set';
die();
}
$query = "SELECT * FROM `users` WHERE `username` = ? LIMIT 1;"
$data = array($_POST['create_user']);
$sth = $dbh->prepare($query);
if(!$sth->execute($data)) {
echo 'Handle SQL Error';
die();
}
if($sth->rowCount() == 0) {
echo 'Unused Username';
}else{
echo 'Used Username';
}
This is what i've found
the $_POST['username'] should be like $_POST['create_user']

Adding a 'check username' to registration form PHP

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.

Duplicate check before adding into database

I have a code which kinda works, but not really i can't figure out why, what im trying to do is check inside the database if the URL is already there, if it is let the user know, if its not the go ahead and add it.
The code also makes sure that the field is not empty. However it seems like it checks to see if the url is already there, but if its not adding to the database anymore. Also the duplicate check seems like sometimes it works sometimes it doesn't so its kinda buggy. Any pointers would be great. Thank you.
if(isset($_GET['site_url']) ){
$url= $_GET['site_url'];
$dupe = mysql_query("SELECT * FROM $tbl_name WHERE URL='$url'");
$num_rows = mysql_num_rows($dupe);
if ($num_rows) {
echo 'Error! Already on our database!';
}
else {
$insertSite_sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
echo $url;
echo ' added to the database!';
}
}
else {
echo 'Error! Please fill all fileds!';
}
Instead of checking on the PHP side, you should make the field in MySQL UNIQUE. This way there is uniqueness checking on the database level (which will probably be much more efficient).
ALTER TABLE tbl ADD UNIQUE(URL);
Take note here that when a duplicate is INSERTed MySQL will complain. You should listen for errors returned by MySQL. With your current functions you should check if mysql_query() returns false and examine mysql_error(). However, you should really be using PDO. That way you can do:
try {
$db = new PDO('mysql:host=localhost;db=dbname', $user, $pass);
$stmt = $db->query('INSERT INTO tbl (URL) VALUES (:url)');
$stmt->execute(array(':url' => $url));
} catch (PDOException $e) {
if($e->getCode() == 1169) { //This is the code for a duplicate
// Handle duplicate
echo 'Error! Already in our database!';
}
}
Also, it is very important that you have a PRIMARY KEY in your table. You should really add one. There are a lot of reasons for it. You could do that with:
ALTER TABLE tbl ADD Id INT;
ALTER TABLE tbl ADD PRIMARY KEY(Id);
You should take PhpMyCoder's advice on the UNIQUE field type.
Also, you're not printing any errors.
Make sure you have or die (mysql_error()); at the end of your mysql_* function(s) to print errors.
You also shouldn't even be using mysql_* functions. Take a look at PDO or MySQLi instead.
You're also not executing the insert query...
Try this code:
if(isset($_GET['site_url']) ){
$url= $_GET['site_url'];
$dupe = mysql_query("SELECT * FROM $tbl_name WHERE URL='$url'") or die (mysql_error());
$num_rows = mysql_num_rows($dupe);
if ($num_rows > 0) {
echo 'Error! Already on our database!';
}
else {
$insertSite_sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
mysql_query($insertSite_sql) or die (mysql_error());
echo $url;
echo ' added to the database!';
}
}
else {
echo 'Error! Please fill all fileds!';
}
As PhpMyCoder said, you should add a unique index to the table.
To add to his answer, here is how you can do what you want to do with only one query.
After you add the unique index, if you try to "INSERT INTO" and it result in a duplicate, MySQL will produce an error.
You can use mysql_errno() to find out if there was a duplicate entry and tell the user.
e.g.
$sql = "INSERT INTO $tbl_name (URL) VALUES('$url')";
$result = mysql_query($sql);
if($result === false) {
if(mysql_errno() == $duplicate_key_error) {
echo 'Error! Already in our database!';
} else {
echo 'An error has occurred. MySQL said: ' . mysql_error();
}
}
mysql_error() will return the mysql error in plain english.
mysql_errno() returns just the numeric error code. So set $duplicate_key_error to whatever the code is (I don't know it off the top of my head) and you are all set.
Also note that you don't want to print any specific system errors to users in production. You don't want hackers to get all kinds of information about your server. You would only be printing MySQL errors in testing or in non-public programs.
ALSO! Important, the mysql functions are deprecated. If you go to any of their pages ( e.g. http://php.net/manual/en/function.mysql-errno.php) you will see recommendations for better alternatives. You would probably want to use PDO.
Anyone who wants to edit my answer to change mysql to PDO or add the PDO version, go ahead.

Multiple Step Registration Form PHP/MySql using sessions

I'm trying to implement a two-step registration form for my site wherein I used 2 separate pages in order to get the information from the user.
First Step:
if($submit)
{
$connect = mysql_connect("localhost","root","");
mysql_select_db("mydb");
$queryreg = mysql_query("INSERT INTO volunteerbio VALUES (<my insert values>)");
}
//gets the latest id added
$query = mysql_query("SELECT MAX(volunteerID) FROM volunteerbio");
$numrows = mysql_num_rows($query);
if($numrows!=0)
{
while($row = mysql_fetch_assoc($query))
{
$dbaccountID = $row['volunteerID'];
}
header("Location: http://localhost/RedCrossCaloocan/registration2_volunteer.php");
$_SESSION['volunteerID']=$dbaccountID;
}
}
?>
What the first step does is that it creates a complete table row wherein the values needed for the second step will be temporarily left with blank values until they are updated in the next step.
Second Step:
<?php
session_start();
$idnum = #$_SESSION['volunteerID'];
$connect = mysql_connect("localhost","root","");
mysql_select_db("mydb");
if($submit)
{
$updateSkills = mysql_query("
UPDATE volunteerbio
SET medicalSkillRating = $medicalRating,
electronicsSkillRating = $electronicRating,
errandSkillRating = $errandRating,
childCareSkillRating = $childCareRating,
counsellingSkillRating = $counsellingRating,
officeSkillRating = $officeRating,
communicationSkillRating =$communicationRating,
carpentrySkillRating = $carpentryRating
WHERE volunteerID = $idnum;
");
}
?>
The second step basically updates the fields which where filled with blank values during the first step in order to complete the registration.
The first step already works and is able to add the values to the database however, I am having a problem on updating the blank values through the second step.
I have a feeling that there may be a problem regarding my usage of sessions in order to get the newly generated ID from the first step, but I just can't figure it out.
You are doing:
header("Location: http://localhost/RedCrossCaloocan/registration2_volunteer.php");
$_SESSION['volunteerID']=$dbaccountID;
The second line MAY never get executed, because you do a redirect before it. I say MAY because it MAY get executed. You have to add exit(); after all redirects to prevent further execution of the script.
Another thing:
Never suppress warnings in PHP using #. The # is almost never needed. So instead of doing:
#$_SESSION['volunteerID'];
You should do:
if (isset($_SESSION['volunteerID'])) {
$idnum = $_SESSION['volunteerID'];
} else {
// something went wrong???
}
I can't see it in your example, but do prevent SQLi vulnerabilities?

Posting data from Database

I am validating a form (checking if field are empty etc and at the end I am using my last validation rule:
//Database Information
//Connect to database
mysql_connect($dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname)or die(mysql_error());
$email = mysql_real_escape_string($_POST['email']);
$cust_code = mysql_real_escape_string($_POST['cust_code']);
//validation e.g.
if (empty($email) + empty($cust_code) > 1){
....
//if everything is ok
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
$data = mysql_num_rows($result);
//get all fields from db and do something
}else{
//My error that is showing up
echo "<span class=\"difftext\">The customer code you have entered is not valid!
<br />
Please enter a valid Customer Code to procceed!
</span>";
Is anything wrong with that because even if I enter the correct cust_code I am getting my error msg instead of my data...
Thank you
EDIT...(I removed, as it is wrong) AND YOU DID WELL... I JUST REALISE WHAT I DID... SORRY...
I have corrected it above.
Thank you
HOW TO DEBUG
Do not put the query string immediately into the mysql method, echo it first
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
echo $sql;
$res=mysql_query($sql);
Are you even connected to the DB?
Error messages are written in English (if it is not MS error messages). Why would you ignore them? Put the error message, read it, try to understand what it says.
An advice, if you will write code that way, it is ok for very small application, for big ones, you need to take a different approach completely to code organization. Which is one of the problems/main problem frameworks are trying to solve for you.
Actually, you are wrong, your error is here, in this two lines:
$sql = mysql_query("SELECT * FROM clients WHERE ID='$cust_code'");
$result = mysql_query($sql);
You are running the query twice.
After the first time $sql holds the resource, then you refer to the resource as if it was a query string. To fix it, change it to:
$sql = "SELECT * FROM clients WHERE ID='$cust_code'";
$result = mysql_query($sql);
You might have more underlying errors, but fix this one first.

Categories