mysql to check if value is more than 0 - php

Here's my code. Actually it run without error but it always enter the first condition even though the value in mysql is more than 0 say for example is 10.
<?php
session_start();
$loginuser = $_SESSION['result'];
$con=mysqli_connect("localhost","root","","leavecalendar");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT leavecount from employee WHERE username = $loginuser[username]";
$resource = mysql_query($sql);
if ($resource == 0) {
echo "ajsdjsdasjd"; <----always enters here
}
else
{
header("insert.php");
}
mysqli_close($con);
?>

First off, you are mixing api's. Dont mix mysqli_* and mysql_*. Just stick with mysqli_*.
$con = mysqli_connect("localhost","root","","leavecalendar"); // mysqli
$resource = mysql_query($sql); // mysql
Second, since you are using mysqli_* now, just use prepared statements.
$sql="SELECT leavecount from employee WHERE username = $loginuser[username]";
Third, dont compare the result set to zero, instead, check how many rows did the result return.
$resource = mysqli_query($con, $sql);
if ($resource == 0) {
Consider this example:
session_start();
if(isset($_SESSION['result'])) {
$mysqli = mysqli_connect("localhost","root","","leavecalendar");
$loginuser = $_SESSION['result'];
$stmt = $mysqli->prepare("SELECT leavecount from employee WHERE username = ?");
$stmt->bind_param("s", $loginuser);
$stmt->execute();
if($stmt->num_rows > 0) {
// if it has results
header("Location: insert.php");
} else {
// if it has NO results
}
}

Problems
1) You can not use
mysql_query($query)
For mysqli
2)
"SELECT leavecount from employee WHERE username = $loginuser[username]"
The username should be single quoted or double quoted.
For ex: "SELECT leavecount from employee WHERE username = 'dineshrawat'";
Solution
<?php
session_start();
$loginuser = $_SESSION['result'];
$con=mysqli_connect("localhost","root","","leavecalendar");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT leavecount from employee WHERE username = $loginuser[username]";
$resource = mysqli_query($con, $sql);
if ($resource == 0) { // If there is no record in result set
echo "No record found";
}
else
{
header("insert.php");
}
mysqli_close($con);
?>

Related

MySQL query no results

I want echo my DB results from Session but i get no results or errors:
$_SESSION['username'];
$link = mysqli_connect("$myHost", "$myUser", "$myPass", "$myDB");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$username = mysqli_real_escape_string($link, $_SESSION['username']);
$sql = "SELECT * FROM users where username = $username";
$result = mysqli_query($link, $sql);
echo $result;
Anyone know why not? Session works.
Thanks
You should change your query, like this:
$sql = "SELECT user FROM yourtablename WHERE username = $username"
Where "user" is what you want to SELECT if you want to select all data, you can use "*", yourtablename is table name of table you want to select.
After your edits, your code should look like
$_SESSION['username'];
$link = mysqli_connect("$myHost", "$myUser", "$myPass", "$myDB");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$username = mysqli_real_escape_string($link, $_SESSION['username']);
$sql = "SELECT * FROM users where username = $username";
if ($result = $link->query($sql)) {
while ($row = $result->fetch_row()) {
var_dump($row);
}
$result->close();
}
More info here
Notice: mysqli_real_escape_string it's not very security. A better option to protect against SQL injections is using prepared statements, more info here

Selecting multiple data from a database through PHP

I have a search form that is able to retrieve the username of a user, however I can't figure out how to get it to return more than that, I want it to display the first names and last names too.
Below is the code at the minute that works, but when I try and add in more variables, for example if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?")) then it doesn't return anything at all and asks to insert a search query.
I have also tried if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE %?%")) and LIKE "%?%")), but no results.
search.php
<?php
include 'connection.php';
if(isset($_POST['searchsubmit']))
{
include 'searchform.php';
$name=$_POST['name'];
if ($stmt = $connection->prepare ("SELECT Username FROM users WHERE Username LIKE ?"))
{
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($personresult);
$stmt->fetch();
?>
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2>
<BR>
<?php
print_r($personresult);
?>
</center>
<?php
}
else
{
echo "<p>Please enter a search query</p>";
}
}
else
{
echo "NOT SET!";
}
You are only calling Username .. You need to be calling *
SELECT * FROM users WHERE Username LIKE ?
This is my personal script I use:
<?php
$dbservername = "localhost";
$dbusername = "db_user";
$dbpassword = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (!empty($_POST["username"])) {
$username = $_POST["username"];
}
if (!empty($_POST["password"])) {
$password = $_POST["password"];
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row["Username"] . " " . $row["Firstname"] . " " . $row["Lastname"] . "<br>";
if ($row["Username"] == $username && $row["Password"] == $password) {
echo "success";
// do more stuff here like set session etc
} else {
$echo "incorrect username and/or password";
}
}
}
?>
Are you initializing the statement object with mysqli_stmt_init?
See mysqli_stmt_init and mysqli-stmt.prepare
If the database server cannot successfully prepare the statement,
PDO::prepare() returns FALSE or emits PDOException (depending on error
handling)
add this line in connection.php right after creating connection object:
$connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
At least, you can trace possible errors
<?php
include 'connection.php';
if( isset( $_POST['searchsubmit'] ) ) {
include 'searchform.php';
$name=$_POST['name'];
if ( $stmt = $connection->prepare ("SELECT `Username`,`firstname`,`lastname` FROM `users` WHERE `Username` LIKE ?") ) {
/* not 100% sure about whether this is required here like this or not but usually a like expression uses '%' as a wildcard */
$var='%'.$name'.%';
$stmt->bind_param('s', $var );
$res=$stmt->execute();
/* 3 columns selected in query, 3 columns bound in results */
$stmt->bind_result( $personresult, $firstname, $lastname );
if( $res ){
$stmt->fetch();
echo "
<center>
<BR>
<h1>Search Results are as follows:</h1>
<h2>USERNAMES</h2><!-- 3 columns/variables -->
{$personresult},{$firstname},{$lastname}
<BR>
</center>";
}
} else {
echo "<p>Please enter a search query</p>";
}
} else {
echo "NOT SET!";
}
$stmt->close();
$connection->close();
?>

If variable is in db then stop- if variable is not- then enter it

i have been trying to get this script done for a while now - im kind of new to php and mysql but i have been trying to get this to check the db for the username and then if the username exists - stop checking the db and if it doesn't exists add it to the db.
here is my code:
//input from application
$test = "wheelsmanx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "User Name Already In Use.";
}if($row["mainusername"] !== $test){
echo "this statement";
[code that inserts into db i can do this part myself]
}
}
$conn->close();
} else {
echo "0 results";
}
$conn->close();
The problem with your code is that you do the INSERT of the new name inside an if statement that has confirmed the existence of that user already. In addition I think you messed up your SELECT statement by selecting all the users.
Look into INSERT ON DUPLICATE for a better way to do it, or revise your code as below.
$sql = "SELECT mainusername FROM CCCpro_test WHERE mainusername = $test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "User Name Already In Use.";
}
else{ //no rows selected therefore the user doesn't exist
[code that inserts into db i can do this part myself]
}
$conn->close();
PLEASE READ I have somewhere to go so I am being lazy so I did not bind the $test variable therefore DO NOT copy and paste this code without updating it to bind the $test variable. Please read this post about PDO and variable binding to prevent SQL injection.
here is my full working code if anyone needs it - it uses the post method - from an html form .... in case some one needs to hack it to pieces for something else
well guys i appreciate all of your help :D but i have found an answer or a way around it i suppose- i thought of it all night and day on how i could make it work and i came up with this
$servername = "127.0.0.1";
$username = "TESTUSER";
$password = "TESTPASS";
$dbname = "TESTDB";
$testusername = $_POST['mainusername'];
$testpassword = $_POST['mainpassword'];
//input from application
$test = $_POST['mainusername'];
$test2 = "0";
//Count switch
$countswitch = "0";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql1 = "INSERT INTO CCCpro_test ( mainusername, mainpassword ) VALUES ('$testusername','$testpassword' )";
$sql = "SELECT mainusername FROM CCCpro_test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if ($row["mainusername"] === $test) {
echo "Im Sorry Username Already In Use";
$countswitch ++;
}
}
if($countswitch == $test2){
echo "User Name Registered";
$db_handle = mysql_connect($servername, $username, $password);
$db_found = mysql_select_db($dbname, $db_handle);
if ($db_found) {
$result1 = mysql_query($sql1);
mysql_close($db_handle);
}
}
if ($countswitch == 3){
echo "this";
}
} else {
echo "0 results";
}
$conn->close();

Retrieve information from database in a variable

I am trying to create a variable in my php code where I can use a value from my database to use user information. Basically, I'm trying to fetch the UserID from the database desikitchen where it matches the variable $dkuser.
Can anyone tell me where I'm going wrong?
$sqlStremail = "SELECT UserID
FROM User
WHERE Name = '$dkuser'";
$result = mysql_query($sqlStremail);
$row = mysql_fetch_assoc($result);
$variable = $row["UserID"];
$sql2 = "INSERT INTO desikitchen.Inventory (ItemName, ItemUser)
VALUES ('{$itemname1}', '{$sqlStremail}')";
$result = mysql_query($sql2);
You better Use MySQLi class library. Something like this:
$mysqli = new mysqli("",$mysqlUser,$mysqlPass,$mysqlTable);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
print FALSE; exit();
}
$query = "SELECT UserID FROM User WHERE Name = '$dkuser'";
$result=$mysqli->query($query);
if($mysqli->query($query)==False) {print mysqli_error($mysqli); exit();}
if($result->num_rows>0)
{ $row = $result->fetch_array();
echo $row["UserID"];
} else
{ echo "User not found"; }

Selecting certain row in mysql

I am completely new to MYSQL and PHP, so i just need to do something very basic.
I need to select a password from accounts where username = $_POST['username']... i couldn't figure this one out, i keep getting resource id(2) instead of the desired password for the entered account. I need to pass that mysql through a mysql query function and save the returned value in the variable $realpassword. Thanks!
EDIT:
this code returned Resource id (2) instead of the real password
CODE:
<?php
$con = mysql_connect('server', 'user', 'pass');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
echo '<br/> ';
// Create table
mysql_select_db("dbname", $con);
//Variables
//save the entered values
$enteredusername = $_POST['username'];
$hashedpassword = sha1($_POST['password']);
$sql = "SELECT password from accounts where username = '$enteredusername'";
$new = mysql_query($sql,$con);
echo "$new";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
It will be a lot better if you use PDO together with prepared statements.
This is how you connect to a MySQL server:
$db = new PDO('mysql:host=example.com;port=3306;dbname=your_database', $mysql_user, $mysql_pass);
And this is how you select rows properly (using bindParam):
$stmt = $db->prepare('SELECT password FROM accounts WHERE username = ?;');
$stmt->bindParam(1, $enteredusername);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$password = $result['password'];
Also, binding parameters, instead of putting them immediately into query string, protects you from SQL injection (which in your case would be very likely as you do not filter input in any way).
I think your code looks something like this
$realpassword = mysql_query("SELECT password
from accounts where username = '$_POST[username]'");
echo $realpassword;
This will return a Resource which is used to point to the records in the database. What you then need to do is fetch the row where the resource is pointing. So, you do this (Note that I am going to use structural MySQLi instead of MySQL, because MySQL is deprecated now.)
$connection = mysqli_connect("localhost", "your_mysql_username",
"your_mysql_password", "your_mysql_database")
or die("There was an error");
foreach($_POST as $key=>$val) //this code will sanitize your inputs.
$_POST[$key] = mysqli_real_escape_string($connection, $val);
$result = mysqli_query($connection, "what_ever_my_query_is")
or die("There was an error");
//since you should only get one row here, I'm not going to loop over the result.
//However, if you are getting more than one rows, you might have to loop.
$dataRow = mysqli_fetch_array($result);
$realpassword = $dataRow['password'];
echo $realpassword;
So, this will take care of retrieving the password. But then you have more inherent problems. You are not sanitizing your inputs, and probably not even storing the hashed password in the database. If you are starting out in PHP and MySQL, you should really look into these things.
Edit : If you are only looking to create a login system, then you don't need to retrieve the password from the database. The query is pretty simple in that case.
$pass = sha1($_POST['Password']);
$selQ = "select * from accounts
where username = '$_POST[Username]'
and password = '$pass'";
$result = mysqli_query($connection, $selQ);
if(mysqli_num_rows($result) == 1) {
//log the user in
}
else {
//authentication failed
}
Logically speaking, the only way the user can log in is if the username and password both match. So, there will only be exactly 1 row for the username and password. That's exactly what we are checking here.
By seeing this question we can understand you are very very new to programming.So i requesting you to go thru this link http://php.net/manual/en/function.mysql-fetch-assoc.php
I am adding comment to each line below
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1"; // This is query
$result = mysql_query($sql); // This is how to execute query
if (!$result) { //if the query is not successfully executed
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) { // if the query is successfully executed, check how many rows it returned
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) { //fetch the data from table as rows
echo $row["userid"]; //echoing each column
echo $row["fullname"];
echo $row["userstatus"];
}
hope it helps
try this
<?php
$con = mysql_connect('server', 'user', 'pass');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
echo '<br/> ';
// Create table
mysql_select_db("dbname", $con);
//Variables
//save the entered values
$enteredusername = mysql_real_escape_string($_POST['username']);
$hashedpassword = sha1($_POST['password']);
$sql = "SELECT password from accounts where username = '$enteredusername'";
$new = mysql_query($sql,$con);
$row = mysql_fetch_array($new) ;
echo $row['password'];
if (!$new)
{
die('Error: ' . mysql_error());
}
mysql_close($con);
?>
<?php
$query = "SELECT password_field_name FROM UsersTableName WHERE username_field_name =".$_POST['username'];
$result = mysql_query($query);
$row = mysql_fetch_array($result);
echo $row['password_field_name'];
?>
$username = $_POST['username'];
$login_query = "SELECT password FROM users_info WHERE users_info.username ='$username'";
$password = mysql_result($result,0,'password');

Categories