Verifying the values from database - php

I'm quite new to mysql tables and I know I should use PDO or mysqli, but this is just an example for school.
Here's my problematic code:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($uporab != $row['uporabnisko'] || $pass != $row['geslo']){
echo '<script language="javascript">';
echo 'alert("Uporabnisko ime ali geslo ni pravilno! Prosim poskusi znova.")';
echo '</script>';
header('Location: index1.php');
}
else{
header('Location: Stranzaindexom.html');
}
}
When I use "while" I get error popped out 5 times (I think it depends on how many values are in table in database), but when I don't use while, than I get checked just first id (first row) in table.. I checked for other answers but I haven't found the proper one..
Any help?
PS: connection to the database is successful, and taking values of table is good to.. So my problems just lay somewhere here.

May be you can try this
Why do we need to select all the records and check all the records the best is to pull only that record which is necessary.
$result = mysql_query("SELECT * name FROM usertable WHERE uporabnisko='$uporab' AND geslo = '$pass'");
if($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo '<script language="javascript">';
echo 'alert("Uporabnisko ime ali geslo ni pravilno! Prosim poskusi znova.")';
echo '</script>';
echo "<script language='javascript'> window.location='index1.php'; </script>";
}
else
{
echo "<script language='javascript'> window.location='Stranzaindexom.html'; </script>";
}

Think reverse check the positive case and give the alert on else like:
if ($uporab == $row['uporabnisko'] && $pass == $row['geslo']){
header('Location: Stranzaindexom.html');
exit();
} else {
echo '<script language="javascript">';
echo 'alert("Uporabnisko ime ali geslo ni pravilno! Prosim poskusi znova.")';
echo '</script>';
}
Or use the username and password at the sql and give limit 1 so you dont need a while becouse it garanteus that result set will be 1 row or 0 row:
mysql_query("SELECT * FROM users WHERE username='".$escapedUsername."' AND password='".$escapedPassword."' LIMIT 1");

Related

Select from multiple MySQL tables

i'm trying to select value from different tables but i face some errors in the result i want to check if there is any values i will echo "Yes" otherwise echo "No"
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username=$_POST['username'];
require_once('dbConnect.php');
$sql="SELECT donator.national_id, needy_people.national_id".
"FROM donator, needy_people".
" WHERE donator.national_id='$username' OR needy_people.national_id='$username' limit 50";
$result=mysqli_query($con,$sql);
if($check>0){
while($row=mysql_fetch_array($sql)){
$check=mysqli_fetch_array(mysqli_query($con,$sql));
}
}
if(isset($check)){
echo'YES';
}else{
echo'Noooo';
}
mysqli_close($con);
}else{
echo'error';
}
can anybody solve this problem help!
When you put as condition if($check>0), $check is not defined yet, so it won't be processed, hence $check stay unset.
Also you should use the empty() function to test existence of values in it
If you're trying to check if a row exists when you run your query consider using the function mysqli_num_rows
if (mysqli_num_rows($result) > 0) {
echo "Has row";
}
$count=mysqli_num_rows($check);
if($count>0)
echo "yes";
else
echo "no";

Wrong part of if statement being executed

When I delete a record from table, I have 8 columns in the table and if more than 8 is entered it must be showed that nothing was deleted. However every number that I give, I get the same response "deleted successfully". This is my code:
$query = "DELETE FROM `order` WHERE orderId = '$_POST[id]'" ;
$result = mysql_query($query);
if(! $result )
{
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}
else
{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}
$result will be a valid result, even when your query won't affect any rows. Use mysql_affected_rows() to check if you deleted anything.
$result = mysql_query($query);
if( mysql_affected_rows() == 0 )
{
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}
else
{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}
side note: the mysql_* functions are deprecated. Don't use them to write new code, especially when you are learning. Use mysqli_*or PDO instead.
You can use mysql_affected_rows
$query = "DELETE FROM `order` WHERE orderId = {$_POST[id]}" ;
mysql_query($query);
if(0 == mysql_affected_rows()){
echo ("$_POST[id] not deleted !<a href='deleteorder.php'>Back</a>");
}else{
echo ("$_POST[id] deleted succesfully! <a href='deleteorder.php'>Back</a>");
}
You are testing if your query ran successfully. It can be successful if it deletes one row or if it deletes none.
Use mysql_affected_rows to determine if you've deleted any rows.
(You'd be better moving to a more modern API though)

Displaying a single value of an attribute using mysql_fetch_field

I want to fetch and display the user_id(that is auto-incremented) from my table after a user is successfully registered and his user information are stored in the same table. Here goes my code. I need help on the last few lines.
if(isset($_POST['register']))
{
$fname=$_POST['fname'];
$mname=$_POST['mname'];
$lname=$_POST['lname'];
$email=$_POST['email'];
$pwd=$_POST['pwd'];
$address=$_POST['address'];
$pincode=$_POST['pincode'];
$phone=$_POST['phone'];
$sql="INSERT INTO `user`(`f_name`,`m_name`,`l_name`,`email`,`password`,`address`,`pincode`,`phone`) VALUES('$fname','$mname','$lname','$email','$pwd','$address','$pincode','$phone')";
$rs=mysql_query($sql);
if($rs==1)
{
echo 'You have been registered successfully!';
}
else
{
echo "Registration failed!";
}
}
$src="SELECT `user_id` from `user` where `email`=$email";
$res=mysql_query($src);
$row=mysql_fetch_field($res);
echo $row;
echo $row[0];
$row is an array of fields, even if in your case it contains only one element. For example, if you use
SELECT a, b, c FROM ...
then $row is an array of 3 elements, $row[0] being for a, $row[1] for b, etc.
mysql_fetch_field — Get column information from a result and return as an object.
$row=mysql_fetch_field($res,0);
if(!row)
{
echo "There is no record";
}
else
{
echo $row->user_id;
}
Check Manual here

Display users First and last name in plain text from the database or give an error

I have a html page that sends value pass to log.php :
<?php
$PHONE = $_POST['pass'];
mysql_connect('host.com', 'user', 'pass'); mysql_select_db('userdb');
$results = mysql_query(sprintf("SELECT FNAME,LNAME FROM `details` WHERE PASS='$PASS'",
mysql_real_escape_string($PASS))) or die(mysql_error()); while($row = mysql_fetch_assoc($results))
{ $rows[1] = $row; }
echo "Welcome ";
echo "$rows[1][FNAME]." ".$rows[1][LNAME]"
echo " you are logged in successfully"
?>
I get the result in log.php file in this form when value 'pass' is not being registered in database:
Welcome [//here user's first & last name if registered or remains blank] you are logged in successfully
I have table 'details' created
FNAME-First name
LNAME-Lastname
BIRTHDAY-Birthday
PHONE- user's no.
PASS- user's password.
My Question is , I want to just display ' You are not registered user' when pass value is not been registered in the database.Any help would be greatfull ?
Just check if you actually get a record or not using mysql_num_rows,
$results = mysql_query(sprintf("SELECT FNAME,LNAME FROM `details` WHERE PASS='$PASS'",
mysql_real_escape_string($PASS))) or die(mysql_error());
if(mysql_num_rows($results) > 0){
while($row = mysql_fetch_assoc($results))
{
$rows[1] = $row;
}
echo "Welcome ";
echo $rows[1]['FNAME']." ".$rows[1]['LNAME'];
echo "You are logged in successfully";
}
else{
//Redirect them back with error message
header("Location: http://www.example.com/index.php?err='You are not registered user'");
}
Note: Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You took value in $phone variable for password and in select query used PASS= $PASS so how can it run?
Change this then run like below:
$results = mysql_query(sprintf("SELECT FNAME,LNAME FROM `details` WHERE PASS='$PHONE'",
mysql_real_escape_string($PHONE))) or die(mysql_error());
if(empty($rows[1][FNAME])){
echo 'You are not registered user';
}
else{
echo "Welcome ";
echo "$rows[1][FNAME]." ".$rows[1][LNAME]";
echo " you are logged in successfully";
}

Have I written the INSERT query correctly? [duplicate]

This question already has an answer here:
entered form data is not saving in mysql db?
(1 answer)
Closed 9 years ago.
Here is my code:
<?php
include('admin/class.php');
Here is my db connection:
$link = mysqli_connect("localhost", "root", "", "timesheet1234");
Here is the action for save button:
if(isset($_POST['save']))
{
$user=$_SESSION['user'];
$sel =$_POST["selpro"];
$mon =$_POST["mon"];
$tue =$_POST["tue"];
$wed =$_POST["wed"];
$thu =$_POST["thu"];
$fri =$_POST["fri"];
$sat =$_POST["sat"];
$sun =$_POST["sun"];
Checking whether the $user is in db are not:
$sql=mysqli_query($link,"select * from emp
where username='".$_SESSION['user']."'");
$res=mysqli_num_rows($sql);
Here it checks whether to insert are not:
if($res==0)
{
$sql1 = mysqli_query($link,"INSERT INTO emp SET username='$user',
project code='$sel',mon=$mon,tue=$tue,wed=$wed,
thu=$thu,fri=$fri,sat=$sat,sun=$sun");
Here the problem comes:
if($sql1){
echo "<script type='text/javascript'>";
echo "alert('TimeSheet Saved..!')";
echo "</script>";
echo "<script type='text/javascript'>";
echo "window.location='my_tm.php'";
echo "</script>";
}
else
{
echo "<script type='text/javascript'>";
echo "alert('Some Error Occured ! Retry..!')";
echo "</script>";
echo "<script type='text/javascript'>";
echo "window.location='my_tm.php'";
echo "</script>";
}
}
}
?>
Isnt the problem with if($res==0)? Because you check if the session user is in the database and store the number of rows in $res. So I would guess that you want to insert the query when $res==1 (one user) and not when there is no user.
Also normally you have complete control over your session variables. So once you store a user in there, you can trust that its there. Unless ofcourse you made mistakes on the authentication process.
Also in your javascript code you want to use window.location.href='my_tm.php to change the url and not just window.location
Try this as your insert query
$sql1 = mysqli_query("INSERT INTO emp SET username='$user',
`project code`='$sel',mon='$mon',tue='$tue',wed='$wed',
thu='$thu',fri='$fri',sat='$sat',sun='$sun'",$link);
The project code column has space

Categories