May be this question will be sort of "stupid-questions", but still...
I'm new to PHP and SQL and I can't understand what I am doing wrong here:
if(isset($_POST[$logButton])) //Checking for login button pressed
{
//Retrieving information from POST method
$uid = $_POST['login'];
$upwd = $_POST['password'];
//SQL Connection
$mysqli = new mysqli('localhost', 'root', '', 'students');
if(!$mysqli)
{
echo "<h1 class='h1A'>Problem accured while connecting to the DB. " . mysqli_error($mysqli) . "</h1>"; //!!!Delete displaying error msg after dev.
}else
{
$sql = "SELECT * FROM login_data WHERE login = ? AND password = ?"; //SQL query
$stmt = $mysqli->prepare($sql) or die("error1"); //No error
$stmt->bind_param('ss', $uid, $upwd) or die("error2");//No error
$stmt->execute() or die("error3");//Giving DB query. No error
$result = $stmt->fetch() or die("error4".mysqli_error($mysqli)); //Putting query's result into assoc array. !!!Delete displaying error msg after dev. No error
echo print_r($result); //It prints out "11" ? ? ?
if(count($result['id']) < 1) //If no rows found.
{
echo "<h1 class='h1A'>Couldn't find account. Please, recheck login and password.</h1>";
die();
}elseif($result['id'] > 1)//If more then 1 row found.
{
echo "<h1 class='h1A'>Caught 9090 error. Contact the administrator, please.".mysqli_error($mysqli)."</h1>";
die();
}elseif($result['id'] == 1) //If only one row's been found.
{
$_SESSION['isLoggedIn'] = true;
redirectTo('/index.php'); //Declared function.
die();
}
}
}
Here is a part of handler function in lib.php file. This file is included to the html-page and the function is used. No errors displayed and when I print_r $result - it prints out 11. Can't get it.
Well, use print_r without echo :
print_r($result);
or pass second parameter to print_r function so it can return string:
echo print_r($result, true);
See http://php.net/manual/en/function.print-r.php for more info.
Related
I need to show website visitor that something went wrong should him making queries to my database fails technically.
Want to get the php code to echo "Sorry! Something went wrong!" if for some reason data fetching failed.
Following are some ways I am trying to accomplish this.
3 samples.
They result in neverending loops thus crashing my browser.
(NOTE the IFs on each sample. That is where the 3 samples differ).
I ranked them according to favourite ....
How to fix this to bare minimum to achieve my purpose ? Would appreciate codes samples. I know how to achieve this with mysqli_stmt_get_result() but need to learn with the mysqli_stmt_bind_result() in procedural style programming. Not into oop yet. Nor pdo.
1.
<?php
//LOOPS NEVERENDING
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';
$conn = mysqli_connect("$server","$user","$password","$database");
$keywords = 'keyword';
$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$keywords);
if(mysqli_stmt_execute($stmt))
{
while($result = mysqli_stmt_bind_result($stmt,$id,$domain))
{
mysqli_stmt_fetch($stmt);
echo 'Id: ' .$id; echo '<br>';
echo 'Domain: ' .$domain; echo '<br>';
if(!$result)
{
echo 'Sorry! Something went wrong. Try again later.';
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
?>
<?php
//LOOPS NEVERENDING
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';
$conn = mysqli_connect("$server","$user","$password","$database");
$keywords = 'keyword';
$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$keywords);
mysqli_stmt_execute($stmt);
while(mysqli_stmt_bind_result($stmt,$id,$domain))
{
if(mysqli_stmt_fetch($stmt)) //If 'Rows Fetching' were successful.
{
echo 'Id: ' .$id; echo '<br>';
echo 'Domain: ' .$domain; echo '<br>';
}
else //If 'Rows Fetching' failed.
{
echo 'Sorry! Something went wrong. Try again later.';
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
?>
<?php
//LOOPS NEVERENDING
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';
$conn = mysqli_connect("$server","$user","$password","$database");
$keywords = 'keyword';
$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$keywords);
if(mysqli_stmt_execute($stmt)) //If 'Query Execution' was successful.
{
while(mysqli_stmt_bind_result($stmt,$id,$domain))
{
mysqli_stmt_fetch($stmt);
echo 'Id: ' .$id; echo '<br>';
echo 'Domain: ' .$domain; echo '<br>';
}
}
else //If 'Query Execution' failed.
{
echo 'Sorry! Something went wrong. Try again later.';
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
?>
Basically, all of the approaches are wrong. If the query fails then there will be an error triggered automatically by PHP as long as you have error reporting enabled, see How to get the error message in MySQLi?. You should not be checking for it manually. Your code is way longer than it needs to be. Consider how it should be done properly:
<?php
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';
// enable error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect($server, $user, $password, $database);
mysqli_set_charset($conn, 'utf8mb4');
$keywords = 'keyword';
$query = 'SELECT id,domain from links WHERE keywords = ?';
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 's', $keywords);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $domain);
// This loop will keep on going as long as fetch() returns true.
// It will return false when it reaches the end
while (mysqli_stmt_fetch($stmt)) {
echo 'Id: ' .$id;
echo '<br>';
echo 'Domain: ' .$domain;
echo '<br>';
}
When you enable mysqli error reporting, your code becomes much simpler. There's no need for any special message to the user. When a query fails then an error will be triggered just like any other PHP error and handled the same way. If you want you can then customize the error page, but that is a completely separate topic.
The loop on mysqli_stmt_fetch() is used to fetch the data from the server. The data will be read row by row, and when there are no more rows mysqli_stmt_fetch() will return false.
mysqli_stmt_bind_result() needs to be called only once. Its purpose is to provide variable placeholders into which the data will be populated.
Their is a mistake in your code that make your code loop forever. In such cases, a while loop in your code is one of the most common cause of this kind of problem.
When you are using any function you should consider to read the documentation of this function and check what kind of errors and what kind of results (returns) it can give you. Functions can throw errors, warning, Exceptions, or return error codes. Also dont underestimate examples on the PHP documentation of each function. It give you a good idea of how things works.
When you are calling a function it's generally good to check the result returned. I will not rewrite all the documentation here but here is an example for mysqli_stmt_bind_result :
https://www.php.net/manual/en/mysqli-stmt.bind-result.php
This part of the procedural example is important for you :
/* bind variables to prepared statement */
mysqli_stmt_bind_result($stmt, $col1, $col2);
/* fetch values */
while (mysqli_stmt_fetch($stmt)) {
printf("%s %s\n", $col1, $col2);
}
Here you can see how mysqli_stmt_bind_result and mysqli_stmt_fetch can be used together to loop through your results.
But this is not perfect for error checking.
The documentation of mysqli_stmt_bind_result says in section Return values :
Returns true on success or false on failure.
So in case of failure of this function you can check for errors this way :
if (!mysqli_stmt_bind_result($stmt, $id, $domain)) {
die("mysqli_stmt_bind_result has failed !"); // of course you can use something more sophisticated than dying...
}
In case of success, and the source of your infinite loop is here, it returns true. So doing while(mysqli_stmt_bind_result($stmt, $id, $domain)) is a mistake, first because you dont have to loop on this function (it's a job for mysqli_stmt_fetch), secondly because mysqli_stmt_bind_result will ever returns true in your case and your while loop will never end.
For mysqli_stmt_fetch now, there is a subtle difference. Check the return values : https://www.php.net/manual/en/mysqli-stmt.fetch.php
Return Value
Description
true
Success. Data has been fetched
false
Error occurred
null
No more rows/data exists or data truncation occurred
Here you have to check for 3 different values and dont forget that null and false can both be evaluated as falsy if you dont take care.
This doesnt allow to display an error :
while (mysqli_stmt_fetch($stmt)) { // is result false or null ? we dont know
printf ("%s (%s)\n", $id, $domain);
}
This is more complete :
$fetchResult = null;
while ($fetchResult = mysqli_stmt_fetch($stmt)) {
printf ("%s (%s)\n", $id, $domain);
}
/* dont forget to use 3 equal signs to also compare variable type */
/* null == false values are considered the same */
/* null === false this also compare variable types, here types are not the same */
if ($fetchResult === false) {
die("mysqli_stmt_fetch failed !");
}
Now you are free to read the documentation of all called functions to do your errors checks.
Also note that another error management (less verbose and error prone) is possible using Exceptions objects like explained by Dharman answer
I keep running into the error where PHP says "We're sorry we can't log you in." according to one of my conditions set even if login is correct and hence my Prepared system to avoid SQL injection fails.
So my code goes like this:
global $connected;
$post = filter_var_array($_POST, FILTER_SANITIZE_STRING);
$pwwd = $post['password'];
$usrn = $post['username'];
$usrn = mysqli_real_escape_string($connected, $usrn);
$pwwd = mysqli_real_escape_string($connected, $pwwd);
if (strlen($usrn) != 0 && strlen($pwwd) != 0 && !empty($post)) {
$usrn = stripslashes($usrn);
$pwwd = stripslashes($pwwd);
$hashFormat = '$2ysomenumber$';
$salt = 'somehashobviously';
$hashF_and_salt = $hashFormat.$salt;
$pwwd = crypt($pwwd, $hashF_and_salt);
if (!mysqli_connect_errno()) {
mysqli_select_db($connected, 'someDbname') or die('Database select error');
} else {
die('Failed to connect to PHPMyAdmin').mysqli_connect_error();
}
$query = "SELECT Username, Password FROM users WHERE Username=? AND Password=?";
$stmt = mysqli_stmt_init($connected);
if (mysqli_stmt_prepare($stmt, $query)) {
//Some error in here somewhere
mysqli_stmt_bind_param($stmt, "ss", $usrn, $pwwd);
mysqli_stmt_execute($stmt);
mysqli_stmt_fetch($stmt);
mysqli_stmt_bind_result($stmt, $check_usrn, $check_pwd);
if (strcasecmp($usrn, $check_usrn) == 0) {
if ($pwwd == $check_pwd) {
echo '<h1 class="text-center">Matches</h1>';
print_r($row);
}
} else {
echo "<h1 class=text-center>We're sorry we can't log you in.</h1>";
}
}
} else { //This is for strlen boolean cond
echo "<h1 class='text-center'>Both fields must not be empty. </h1>";
}
I used to use a login page without prepared statements which was working, but I realised I need to do this for better security. My database is working fine so the problem is near where I added the comment "//Some error in here somewhere".
I am a relatively new PHP programmer that is yet a first year student trying daring new things in the holidays! Will openly read all the help I get, thank you!
First i didn't see your connection code for connection to the database which is like this.
$connected = msqli_connect(host,user,password,db_name) ; than you don't need to call mysqli_select_db()function.
Secondly you are checking your connectinon from mysqli_connect_errno() function which return 0 as integer (not boolean) if no error code value for last mysqli_connect() function.
Third there is no need to Initializes prepare statement.
Fourth is mysqli_stmt_bind_reslut() comes before the mysqli_stmt_fetch(). see note point in manual
Use hash_equals() function to match password instead of ===. see the warning section in crypt
$connected = msqli_connect(host,user,password,db_name) ;
if(!$connected)
{
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
}
echo "Your connection is successful . "
if($stmt = mysqli_prepare($connected,$query))
{
mysqli_stmt_bind_param($stmt, "ss", $usrn, $pwwd);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $check_usrn, $check_pwd);
mysqli_stmt_fetch($stmt);
/* Now do Your Work */
} else
{
/* still prepare statement doesn't work */
} `
I've searched thoroughly and nothing seems to be working; I have this code here which posts into my database but the problem is I am trying to run a conditional which checks if a row exists using the mysqli_num_rows function, but it is not actually working. I have tried many different versions and other functions as well such as mysqli_fetch_row, but nothing seems to work. Here is my code:
if (!empty($_POST)) {
$db_conx="";
$name = $_POST['name'];
$module = $_POST['module'];
$secret = $_POST['secret'];
$uid1 = $dmt->user['uid'];
$queryA = "INSERT INTO table_a (uid1,name,module,secret) VALUES ('$uid1','$name','$module','$secret')";
$resultA = mysqli_query($db_conx,$queryA);
$queryB = "SELECT 1 FROM table_a WHERE name='$name' LIMIT 1";
$resultB = mysqli_query($db_conx,$queryB);
$resultC = mysqli_query($db_conx,$queryB);
$query = mysqli_query($db_conx,"SELECT * FROM table_a WHERE name='$name'");
if (empty($name)||empty($module)||empty($secret)) {
echo "Oops! Can't leave any field blank <br />";
exit();
} elseif(mysqli_num_rows($query) > 0){
echo "name already exists.";
exit();
} elseif ($db_conx->query($queryA) === TRUE) {
echo "New record created successfully.";
exit();
} else {
echo "Error: " . $queryA . "<br>" . $db_conx->error;
exit();
}
}
As you can see the query appears to run but indeed does not do what it's told.
The first line of code inside your IF is destroying the variable you are using to hold the database connection
if (!empty($_POST)) {
$db_conx=""; // get rid of this line
So basically nothing using the mysqli API will work.
ALSO:
Add these as the first 2 lines of a script you are trying to debug
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
as you are obviously not readng your php error log
I'm creating simple game for Facebook. All users who used app are written to database. I need always check If user already exists Is in database, how to do that correctly?
So I have variable $name = $user_profile['name']; It successfully returns user's name
And this is my part of code to check If user already exists in database.
$user_profile = $facebook->api('/me');
$name = $user_profile['name'];
$mysqli = new mysqli("host","asd","pw","asdf");
echo "1";
$sql = "SELECT COUNT(*) AS num FROM myTable WHERE userName = ?";
echo "2";
if ($stmt = $mysqli->prepare($sql)) {
echo "3";
$stmt->bind_param('s', $name);
echo "4";
$stmt->execute();
echo "5";
$results = $stmt->get_result();
echo "6";
$data = mysqli_fetch_assoc($results);
echo "7";
}
if($data['num'] != 0)
{
echo "bad";
print "user already exists\n";
} else {
echo "good";
$apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
print "No user in database\n";
}
}
This code not working, It should post data on user's wall If user not exists in database. I spent many time to find reason why, but unsuccessfully. After debugging It don't show any errors. To find which line is incorrect after every line I used echo "number" so now I know which line is incorrect. It prints 1 2 3 4 5 and stucks. (everything what are below the code not loading.) So that means this line $results = $stmt->get_result(); is incorrect. But I misunderstood what's wrong with this line?
If I comment this line all code loading (then print 1 2 3 4 5 6 7 No user in database! and It post data on user's wall.) but in this case program always do the same, not checking database.
Also I've tried to change COUNT(*) to COUNT(userName), but the same.
So could you help me, please?
I've read this: Best way to check for existing user in mySQL database? but It not helped me.
P.s. In this case i need to use FB username.
Can you try this, $stmt->fetch() instead of mysqli_fetch_assoc($results)
$mysqli = new mysqli("host","asd","pw","asdf");
echo "1";
/* Create the prepared statement */
$stmt = $mysqli->prepare("SELECT COUNT(*) AS num FROM myTable WHERE userName = ?") or die("Prepared Statement Error: %s\n". $mysqli->error);
/* Execute the prepared Statement */
$stmt->execute();
/* Bind results to variables */
$stmt->bind_result($name);
$data = $stmt->fetch();
if($data['num'] > 0)
{
echo "bad";
print "user already exists\n";
} else {
echo "good";
$apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
print "No user in database\n";
}
/* Close the statement */
$stmt->close();
Ref: http://forum.codecall.net/topic/44392-php-5-mysqli-prepared-statements/
I have the next php code:
<?php
mysqli_report(MYSQLI_REPORT_ALL);
$mysqli = new mysqli("localhost","mybd","mypass");
if ($mysqli->connect_errno) { echo "Error connect<br/>"; }
else {
$mysqli->select_db("database1");
if ($result = $mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Default database is %s.\n", $row[0]); // shows correct database selected
$result->close();
}
$sentencia = $mysqli->prepare("select pass from users Where name ='ronald'");
echo "Prepare error:".$mysqli->error."<br/>";
if (!$sentencia) echo "<br/>sentencia is null<br/>";
if ($sentencia->execute)
{
$sentencia->bind_result($cpass);
$sentencia->fetch();
echo "Passwd:".$cpass."<br/>";
$con="checkpass";
if (($con!=$cpass) && (md5($con)!=$cpass))
{
echo "OK<br/>";
}
else echo "NO OK<br/>";
}
else echo "<br/>Error execute: ".$mysqli->error;
}
mysqli_report(MYSQLI_REPORT_OFF);
?>
Problems are:
- $mysqli->error shows nothing. No error. Always empty string.
- $sentencia->execute always return null, and then always echo "Error execute:", but no information about error.
Database selected shows ok. It select the right database. This is an example. Really the name is passed with "$sentencia->bind_param("s",$user);" but with this, I get apache error of "no object".
I don't know why it happens. The SQL is checked and is Ok.
Thanks.
Shouldn't execute be a function nor property?
http://php.net/manual/en/mysqli-stmt.execute.php
if ($sentencia->execute())
{
}