Posting data from Database - php

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.

Related

How to echo an item from a database

I am still in the process of learning PHP so forgive me for the poor code.
I am attempting to get the users first name to output once they have logged in, however nothing is returning, please may I have some help.
<?php
session_start();
$DATABASE_HOST="localhost";
$DATABASE_USER="root";
$DATABASE_PWORD="";
$DATABASE_NAME="registration";
$connection=mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PWORD, $DATABASE_NAME);
if (mysqli_connect_errno()){
//if there is an issue with connecting to the database, ends code and displays the error
die("failed to connect to server: " .mysqli_connect_error()); //kills program
}
if (!isset($_POST['email'], $_POST['pswd'])){ //checking if both fields were inputted into on the form, isset()checks if data exists
//unable to get data
die("please fill in both email and password"); //kills program
}
$email = mysqli_real_escape_string($connection, $_POST['email']); //saves input as string, preventing misinterpretation
$password = mysqli_real_escape_string($connection, $_POST['pswd']);//saves input as string, preventing misinterpretation
$SQLstatement = "SELECT * FROM users WHERE email='$email' and password='$password'"; //querys the database for match
$Queryresult = mysqli_query($connection, $SQLstatement) or die(mysqli_error($connection)); //runs the query
$rowsQueryResult = mysqli_num_rows($Queryresult);//number of 'emails' in database where the emails match
$dbFirstName=$rowsQueryResult ['firstName'];
if ($rowsQueryResult==1){//if the number of emails where a match is made, is 1
echo "Welcome $dbFirstName <br/> ";
echo "successful login. <a href='accountPage.php'>Click</a> here to access the accounts page"; //successful login, links to accounts page
$_SESSION['firstName']=$dbFirstName;
}else{ //if matches are 0 or >=2
die ('unsuccessful login'); //kills program
}
?>
Thank you for your time and help
This problem can be solved by using the mysqli_fetch_assoc() function in place of mysqli_num_rows(). However, I would recommend you to use PDO since it's easier to implement and more readable.
The mysqli_num_rows() function returns the number of rows in a result set.
$rowsQueryResult = mysqli_num_rows($Queryresult);`
will give number of 'emails' in database where the emails match.
You need to use mysqli_fetch_assoc() as
$row = mysqli_fetch_assoc($Queryresult);
$dbFirstName=$row['firstName'];

Echo out user information in the same table to their page base on their store information without echoing out the same information to another user

First of all I stored users in the same table and I created a page called welcome.php, where I want it to be echoing out user info from MySQL based on their entry.
Now when I created first user and echo it out to this welcome.php, it comes out from the table, and if I create another user info in the same table for it to echo out at the same welcome.php based on the user login info such as, if I create a user called John Fred etc and a user called Michael Kenneth etc.
So user John Fred comes out to the welcome.php with its information from the same table, and then user Michael Kenneth doesn't come to welcome.php when i sign with user Michael Kenneth instead it shows only user John Fred. I don't know where this error comes from; maybe from the login.php, or from welcome.php.
Here is my code echoing in welcome.php
<?php
$tnumber2 = "{$_SESSION['tnumber2']}";
// Connect to the database
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$Tname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<? echo $rows['tnumber2']; ?>
Another script for other user info which I store for another table:
<?php
// Connect to the database
$tnumber2 = "{$_SESSION['tnumber2']}";
$db = mysql_connect("$Sname","$Uname","$Pname") or die("Could not connect to the Database.");
$select = mysql_select_db("$Dname") or die("Could not select the Database.");
$sql="SELECT * FROM `$UPname` LIMIT 0, 25 ;";
$result=mysql_query($sql);
?>
<?php
while($rows=mysql_fetch_array($result)){ // Start looping table row
?>
<? echo $rows['pdate']; ?>
<?php
// Exit looping and close connection
}
mysql_close();
?>
And here is my login.php in this case am using one input form:
<?php
session_start();
ob_start();
?>
<?php
if ($_POST['submit']) {
$tnumber2 = $_POST['user'];
if ($tnumber2) {
require("connect.php");
$query = mysql_query("SELECT * FROM users WHERE tnumber2='$tnumber2'");
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_assoc($query);
$id = $row['id'];
$tnumber2 = $row['tnumber2'];
if ($tnumber2 == $tnumber2) {
$_SESSION['id'] = $id;
$_SESSION['tnumber2'] = $tnumber2;
header("Location: welcome.php");
}
}
else
include "error.php";
}
}
?>
I have tried all I can on this, maybe I might be a fool to think that such thing is possible but I am not a PHP professional, just a learner, please any help will be gladly appreciated.
Assuming the session has indeed stored the data of the logged-in user, you need to change "welcome.php" so it reads the correct user with a WHERE clause:
<?php
// Retrieve the ID of the user (and untaint it too)
$id = (int) $_SESSION['id'];
// Connect to the database (I've removed the unnecessary quotes)
$db = mysql_connect($Sname, $Uname, $Pname) or die("Could not connect to the Database.");
$select = mysql_select_db($Dname) or die("Could not select the Database.");
// Here is the query from the users table, we're selecting one user here
$sql="SELECT * FROM `users` WHERE `id` = $id;";
$result = mysql_query($sql);
$rows = mysql_fetch_array($result);
?>
<!-- Let's see what is in rows now, should be just one record -->
<?php print_r($rows) ?>
I would advise that you try to understand each part of the code above, and indeed the same for the code you have - don't just copy-and-paste without knowing what each bit does. If you get stuck on something, don't be afraid to look it up in the manual!
I've used print_r to just dump the row result - you can use the contents of that to determine what columns and other data you wish to extract out of it. After you have done that, the print_r can be removed.
Bear in mind that your login is not testing for password correctness - it only checks that someone has entered a particular username in login.php. If you want users to log on with a username and password, that needs to be designed and implemented as well. There are many questions on this site with best-practice techniques on how to do that, if that's of interest to you.
It has, incidentally, been rather difficult to understand what you are doing. I don't think this is a problem with your English, which seems fine to me. Rather, it's worth remembering to write in short sentences (no more than 20 words, say) and short paragraphs (no more than 4 or 5 sentences). And keep your descriptions as short as you can - it makes the difference between people helping you and their deciding they don't understand what you are trying to do. I expect this advice would be just as relevant in your native language as well!
Also, remember to add as much useful information to a question as you can, and if people ask for clarification, make sure you answer all their questions. Remember that people here are volunteers, and you need to make their job as easy as possible.

MYSQL Tables Picky About Fields?

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());

If Else to look into SQL permissions

So I'm trying to write a temp way to login to the admin panel using an if else statement while I read up on PDO. If someone could tell me where the error lies here it would be much appreciated.
I've updated my code after looking around a little bit, but I still have the issue of nothing showing up where my code belongs and pulling the information it should.
<?php
$admin = $_SESSION['admin_login'];
$con=mysql_connect("$server","$user","$pass");
if
(!$con)
{
die('Could not Connect' .mysql_error());
}
mysql_select_db($webdb, $con);
$result=mysql_query("SELECT * FROM permissions WHERE username= '$admin' ");
$row = mysql_fetch_assoc($result);
if ($row['permissions']=="3")
{
echo 'Admin Panel';
}
elseif ($row['permissions']=="1")
{
echo 'include acp_error.php';
}
?>
Is what I've updated to; Does anyone see any issue here?
mysql_query returns a statement HANDLE, not the value(s)/row(s) you're trying to select. YOu need to FETCH a row of data to be able to get the values you need to compare.
$result = mysql_query(...) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['somefield'] == 3) {
...
}
Please note that things like
"$webdb"
are pointless cargo-cult programming. A simple
$webdb
is all that's needed for such things. There is not point in creating a new string, whose sole contents are the contents of a variable - just use the variable itself.
As well, note that you're vulnerable to SQL injection via that $_SESSION value you're using in the query. If that's a text value, and contains user-supplied data, your server is trivial to pwn.

login function is not working properly

Hello I facing a strange problem; I am using this code to check the login data with my db
include("includes/config.php");
include("includes/database.php");
$name = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM info_user WHERE user_name = '$name' AND password = '$pass'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
echo $row['user_name']. " - ". $row['password'];
if (mysql_num_rows($sql)) {
echo "success";
}
else
{
echo "failed";
}
here, when i succeed it shows success but any blank input or wrong input is not showing the failed message why? and how can I solve it? is there any better way to check the login? please help
Thanks in advance
First off:
$row = mysql_fetch_array($result) or die(mysql_error());
If you pass along a wrong username or password, mysql_fetch_array() will return FALSE, because there is no rows to take from. This results in your or die(mysql_error()) part being executed, which means your script dies and outputs nothing since mysql didn't fail - which again means that mysql_error() has nothing to return to you.
Secondly, you are using mysql_num_rows() on the $sql string, not on the $result variable which actually contains a mysql resource that you should be using.
You should also check the mysql_num_rows() before using mysql_fetch_array() so that you don't try to pull out some data you don't have available.
Lastly, your solution is full of security flaws. You are passing along raw post data to your mysql database which makes you vulnerable to sql injection and you are storing your passwords as plain text values in your database (not plain text files, just plain text values).
You should google sql injection and password hashing to improve your security.
Try this:
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
echo "success";
} else {
echo "failed";
}

Categories