I have been trying to get this code to update, and it just will not work. I've been re-reading it and looking at other examples for hours and need some help to get this to work. It is a basic UPDATE script for a membership table in mysql database. I have mysql version 5.0.91. Nothing I have tried is working. When uploaded and tested in browser, returns echo "update query failed" I bolded the part where it is failing. I just can't find out why. When I check mysqladmin, the table is not updated.
$host="mysqlhost"; // Host name
$username="mysqlusername"; // Mysql username
$password="mysqlpassword"; // Mysql password
$db_name="mydbname"; // Database name
$tbl_name="brothers"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$mymname=$_POST['mymname'];
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$myconfirmpassword=$_POST['myconfirmpassword'];
$mysnumber=$_POST['mysnumber'];
$myemail=$_POST['myemail'];
if ($mypassword !== $myconfirmpassword) {
die ("passwords do not match. Try again!");
if (isset($_COOKIE['fname'])) {
$myfname = ($_COOKIE['fname']);
}
else {
die('could not find cookie fname');
}
if (isset($_COOKIE['lname'])) {
$mylname = ($_COOKIE['lname']);
}
else {
die('could not find cookie lname');
}
$sql="SELECT * FROM $tbl_name WHERE fname='$myfname' AND lname='$mylname'";
$result=mysql_query($sql)or die("no sql");
while($row = mysql_fetch_array($result))
{
$fname=$row['fname'];
if (!$fname) {
die('variable not received');
}
$lname=$row['lname'];
$position=$row['position'];
$committee=$row['committee'];}
if($mypassword==$myconfirmpassword) {
$query= "UPDATE brothers
SET `mname`='$mymname' WHERE `fname` ='$fname'";
$chechresult= mysql_query($query) or die (mysql_error());
if (!$checkresult) echo 'update query failed';
elseif ($checkresults) {
echo'update query success';
setcookie('position', $position, time()+86400,'/');
setcookie('committee', $committee, time()+86400,'/');
$headsuccess=header( "location:done_registration.php");
$headsuccess;
if (!$headsuccess) {
die('Could not redirect success registration'); }
}
}
else{
$headlogin=header( "location:error_registration.php");
$headlogin;
if (!$headlogin) {
die('Could not redirect registration error'); }
}
$chechresult= mysql_query($query) or die (mysql_error());
if (!$checkresult) echo 'update query failed';
you misspelled "k" with "h" in "$chechresult="
Try to print $query string that contains the UPDATE order and after execute it in mysql console.
You've misspelled $chechresult - should be $checkresult; also, $fname should be $myfname!
It is probably worth echoing out $query to the screen, and trying that directly in your database - either on your console or in phpMyAdmin. Since $fname is empty (wrong var) your WHERE clause is wrong; at a guess it is affecting zero rows, and so is executing correctly.
Bear in mind that you have some SQL injection security issues in this code - make sure you escape your values before adding them to a query. Better yet, if you upgrade to PDO, you can use parameterisation, which will do the escaping for you.
Related
I am creating a web based application, and I am using PDO for my database. I have a query that selects everything from login table where username=something and password=something.
My code:
$query = $db->prepare("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindParam(':username',$username);
$query->bindParam(':password',$password);
$query->execute();
However I want to check if the query returned true or false. For example in mysql we used to say:
$query = mysql_query("SELECT * FROM login WHERE username='$username' AND password='$password' ");
if($query == false){
die(mysql_error());
}
My question is, how do I check if the query returned false or true using PDO and gives an error? This will help me get errors on my code during development.
What am I going to replace the mysql_error() with?
We set PDO in exception mode.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
We wrap queries with try/catch block. If an Exception is thrown, we catch it. That's the equivalent of using if(!mysql_query($query)) echo mysql_error();
Your example would be
try
{
$query = $db->prepare("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindParam(':username',$username);
$query->bindParam(':password',$password);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
echo "Whoopsie, an error occurred! Message: ". $e->getMessage();
}
define('DB_NAME','swiftx');
define('DB_USER','root');
define('DB_PASSWORD','123456');
define('DB_HOST','localhost');
if (isset($_POST['submit'])){
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}else{
echo("Database Connected");
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$value = $_POST['name'];
$value2 = $_POST['attendance'];
$sql = "INSERT INTO people (Name,Email) VALUES ('$value','$value2')";
if(!mysqli_query($sql)){
die ("ERROR:". mysqli_error()); //error here <<<<<<<<
}
}
mysqli_close($connection);
why is mysql returing error "mysqli_query() expects at least 2 parameters"
i am following a website tutorial , i double check again and again , i have done noting wrong , can anyone help me fix it ? i have no idea what i doing wrong.
for mysqli_query() we need to pass two parameters
$query
$link_identifier
in your case $query is $sql and $link_identifier is $connection..it mean you need to use mysqli_qeury() in this way
mysqli_query($sql, $connection)
Your error "mysqli_query() expects at least 2 parameters" is pretty self-explanatory. It expects two parameters you are giving just one.
Try this:
if(!mysqli_query( $connection, $sql) ){
I am trying to fetch data from table. Table contains the data and query is true. Even why following query says $u and $t are not define. While condition becoming false.
I manually checked in database, it was showing results.
$url = "http://paulgraham.com/";
$user_id = "123";
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$result = mysqli_query($con,"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id."");
while ($row = #mysqli_fetch_array($result))
{
echo "hi";
$t = $row['title'];
$u = $row['url'];
}
echo "title is : $t";
echo "url is : $u";
Giving your SQL query :
"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id.""
You can see you are mixing url and userid... Change to :
"SELECT * FROM post_data WHERE userid =".$user_id." and url=".$url.""
Also define your $t and $u variables before your loop in case you have no record.
Next time, try to var_dump your generated query to test it.
If you were able to see the errors the DBMS is reporting back to PHP then you'd probably be able to work out what's wrong with the code.
Before the 'while' loop try...
print mysql_error();
(the obvious reason it's failing is that strings mut be quoted in SQL, and you've got the parameters the wrong way around)
I am writing a code that will check 2 different tables to determine the privileges the user will have. The code looks like this:
$query1 = ("SELECT 1 FROM `customers` WHERE `Email` = '$email' AND `Password` = '$password'");
$query2 = ("SELECT 1 FROM `admins` WHERE `Email` = '$email' AND `Password` = '$password'");
$result1 = mysql_query($query1) or die(mysql_error());
$result2 = mysql_query($query2) or die(mysql_error());
if (mysql_num_rows($result1) == 1) {
// Log user in as a Customer
exit;
} else if (mysql_num_rows($result2) == 1) {
// Log user in as an Admin.
exit;
} else {
// Direct user to registration page.
}
Can anyone look at this and tell me if there would be any security risk by doing it this way? Thank you in advance for your help!
Firstly you have a change that your code is only known by you.
Secondly you have to check the input data. email and password area is not safety. You should prevent SQL injection. Otherwise your code is not secure.
By the way i'm offering you IP restricted login for admins. I'm using this. And it is more secure.
One big problem here is that the code is vulnerable for sql injections.
Which basicly means that the user could put code in the email or password form to bypass the check you have here.
A start would be to perform the following to your input BEFORE you use them in your query:
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
Though, the mysql library is not recommended by php, rather read about prepared statements in pdo here: http://www.php.net/manual/en/ref.pdo-mysql.php
But you can try the mysql_real_escape_string to have a first security measure against sql injections.
This is insecure if for example my password was
OR 1=1
I get access. Use mysql prepared statements
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("SELECT 1 FROM customers WHERE Email = (?) AND Password = (?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("ss", $email, $password)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
?>
Something is wrong with this code.
#!/use/bin/perl
use strict;
use warnings;
use Frontier::Daemon;
use DBI;
sub credentials {
my ($username, $password) = #_;
my $tablename = "users";
my $user = "db_user";
my $pw = "db_pass";
$dbh = DBI->connect('DBI:mysql:database;host=localhost', $user, $pw, {RaiseError => 1});
$sql = "SELECT username, password FROM $tablename";
$sth = $dbh->prepare($sql);
$sth->execute or die "SQL Error: $DBI::errstr\n";
if ($sth->rows > 0) {
$login_response = "Login Successful";
} else {
$login_response = "Invalid Credentials";
return {'login' => $login_response};
die();
}
}
$methods = {'login.credentials' => \&credentials,};
Frontier::Daemon->new(LocalPort => 8080, methods => $methods)
or die "Couldn't start HTTP server: $!";
This is another problem with your code - you're not doing anything with the supplied username and password. You need to add a where clause to your SQL statement, so:
my $sql = 'SELECT * FROM users WHERE username = ? AND password = ? ';
my $sth = $dbh->prepare($sql);
$sth->execute($username, $password);
However, given that your example is selecting all records from the 'users' table, I'd have thought that credentials() would at least be returning some rows. However, I'm afraid that I've not used Frontier::Daemon in the past, so I'm not able to help on that front.
I also can't see how this code would work given that you are using strictures. $dbh, $sql, $sth and $login_response haven't been declared. So make sure that you're using 'my' in the right places - as per my example above.
To fix the problems you mentioned with returning the correct string - the logic in your if statement isn't quite right. You are returning the string 'Login Successful' when there's a successful login and the hashref { login => $login_response } when no user could be found.
I think the confusion arose from the layout of the braces. I must stress that you try and indent you code properly, which will make it much more readable to yourself and other developers when debugging and maintaining the code in the future.
The following logic should do the job.
if($sth->rows > 0){
return "Login Successful";
}
return "Invalid Credentials";