php num->rows not working - php

I keep getting an error, even though I am 100% sure I followed the example that is found in the PHP manual.
The simplified version of the code can be found below.
note: connection to the database is ok.
EDIT: I keep getting an "Catchable fatal error: Object of class mysqli_stmt could not be converted to string" error.
EDIT: Now I keep getting "Mission Failed" even though I am sure that the row count should be 1.
Here's the coode used:
# $db = new mysqli('localhost', 'USER', 'PASSWORD', 'DATABSE');
$email = $db->prepare("select * from members where email = ?");
$email->bind_param('s', $email);
$email->execute;
$email->store_result;
$email->num_rows;
if ($email > 0) {
echo "<p>This e-mail is already in use, please try again with another e-mail.</p>";
exit;
} else {
echo "mission failed";
}
exit;
EDIT:
# $db = new mysqli('localhost', 'USER', 'PASSWORD', 'DB');
if ($db->connect_errno) {
echo "<p id=\"signup_confirmed\">Error: could not connect to database. Please try again later.</p>";
exit;
}
$checkRow = $db->prepare("select * from members where email = ?");
$checkRow->bind_param('s', $email);
$checkRow->execute;
$checkRow->store_result;
if ($checkRow->num_rows > 0) {
echo "<p id=\"signup_confirmed\">This e-mail is already in use, please try again with another e-mail.</p>";
exit;
} else {
echo "<p id=\"signup_confirmed\">Row checking has failed</p>";
}

change
$email->num_rows();
to
$email->num_rows;
in your code
New edit
$count = $email->num_rows;
if ($count > 0) {
echo "<p>This e-mail is already in use, please try again with another e-mail.</p>";
exit;
} else {
echo "mission failed";
}
More edit
change this to
$email = $db->prepare("select * from members where email = ?");
$email->bind_param('s', $email);
this
// you are over riding your $email value with the query thats the reason its not working
$query= $db->prepare("select * from members where email = ?");
$query->bind_param('s', $email);

# $db = new mysqli('localhost', 'USER', 'PASSWORD?', 'DATABSE');
$query_email = "select * from members where email = ?";
$email = $db->prepare($query_email);
$email->bind_param('s', $email);
$email->execute();
$email->store_result();
if ( $email->num_rows > 0) {
echo "<p id=\"signup_confirmed\">This e-mail is already in use, please try again with another e-mail.</p>";
exit;
}

$email is a result set, an object.
It will hold data returned from SQL operation.
You need to get the num_rows() in a variable.
Corrected code:
$cnt = $email->num_rows;
if ($cnt > 0) {
OR
if ($email->num_rows > 0) {

instead of
if ($email > 0) use if ($email->num_rows() > 0)

Related

Echo database user Name with Posted email

I'm trying to get the user's name from a database after posting his email on a form but its not showing the name, if I add a success message it shows it so it's working but its not showing me the name :(
<?php
$conn = mysqli_connect("xxx", "xxx", "xxxxxxxx", "xxxxxxx");
$email = $_POST['email_r'];
$sqlr = "SELECT * FROM participantes WHERE email='$email'";
$result = $conn->query($sqlr);
if(!$row = mysqli_fetch_assoc($result)) {
echo "Email Incorrecto: No se a registrado.";
} else {
echo "your name is: ->" . $row['name'] . " <- that is it.";
}
?>
If I had to guess, I'd say your table does not have a name column. Either that or the matching record has an empty name value.
This should at least help you pinpoint any potential issues as well as resolve your SQL injection vulnerability...
<?php
// show any errors
ini_set('display_errors', 'On');
// show all errors
error_reporting(E_ALL);
// make MySQLi throw exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect("xxx", "xxx", "xxxxxxxx", "xxxxxxx");
// safely get the request parameter
$email = isset($_POST['email_r']) ? $_POST['email_r'] : null;
// Prepare a statement with a placeholder for the "email" parameter
$stmt = $conn->prepare('SELECT `name` FROM `participantes` WHERE `email` = ?');
// bind the parameter
$stmt->bind_param('s', $email);
$stmt->execute();
// bind results. This seems easier than fetch_assoc IMHO
$stmt->bind_result($name);
// fetch records, if any
if ($stmt->fetch()) {
echo 'your name is: ->', $name, ' <- that is it.';
} else {
echo "Email Incorrecto: No se a registrado.";
}
$stmt->close();

SQL prepared statements. PHP

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.

How to use SELECT with WHERE & AND in conditional checks using PHP and MySql

On my server, I am attempting to find a specific string in a database table, if that string is found, I want to check to see what an integer value is in another field of the same row and UPDATE that integer if it is needed, or exit the PHP script.
The code below is only some of what I have tried. I don't see what is incorrect with the commands, and there are no error messages produced when it is ran/called.
What happens is, if the string is found, the script automatically runs the $there query.
What do I need to do to make this work correctly?
Thank you very much.
// This script checks to see if a member name sent by the page exists in the database.
//-------------------------------------------------------------
// The database section starts here.
$servername = "localhost";
$username = "manager";
$password = "********";
$dbname = "golf_ledger";
//------------------------------
// Make a connection with the server.
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check the connection.
if($conn === false){
die("ERROR: Couldn't connect. " . mysqli_connect_error());
}
else {
echo "The connection worked."."<br>"."<br>";
}
//------------------------------------------------------------------
// This is the test string to be searched for.
$memName = "Richardson";
//----------------------------------------
// Populate $result with the search query.
// Database name Table name
$result = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName'");
if(mysqli_num_rows($result) == 0) {
echo "Sorry, the name was not found";
die();
}
//----------------------------------------
// Something is wrong with this one, possibly.
$there = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName' AND `member_table`.`pay_Status` = 1");
// "if ($there)" is the same as "if ($there == true)" in PHP.
if ($there == true) {
echo "The name has been found, and they have paid.";
die();
}
//----------------------------------------
$notThere = mysqli_query($conn,"SELECT * FROM `golf_ledger`.`member_table` WHERE `member_table`.`name` = '$memName' AND `member_table`.`pay_Status` = 0");
if ($notThere == true) {
mysqli_query($conn,"UPDATE `golf_ledger`.`member_table` SET `pay_Status` = 1 WHERE `member_table`.`name` = '$memName'");
echo "The name has been found, they have NOT paid, but the status has been updated.";
die();
}
Instead of this code:
if ($there == true) {
echo "The name has been found, and they have paid.";
die();
}
try that:
// Check if found any records
if (mysqli_num_rows($there) > 0) {
echo "The name has been found, and they have paid.";
die();
}

php PDO mysql - behavioural query

Happy New Year to all. I need to point out I am trying to use PDO exclusively and I'm a relative noob to using PDO, so please excuse the question if it appears plainly obvious.
I'm having a bit of a stupid moment because I cannot seem to understand a few things as to why a relatively simple email validation system I have (tried) to write is not quite working correctly. Everything is ok until the php at the end of the validation link is setting the email address as being validated. Here is my code, followed by questions:
Firstly I have an include file that holds the DB login. It looks like this:
<?php
// DATABASE SETTINGS
$hostname = "127.0.0.1";
$username = "devProduction";
$password = "ienx3rybcisuc";
$database = "devProduction";
try {
$conn = new PDO("mysql:host=$hostname; dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8"); // Sets encoding UTF-8
// close the database connection (removed as I do this at the end of each call)
//$conn = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
?>
And then in the page that actually received the user after they click on the link sent out to their email:
<?php
// Grab our includes
include '../conf/Funcs.php';
include '../conf/DBconfig.php'; // (This is the file displayed above)
require_once '../conf/Mobile_Detect.php';
// Check out what device is looking at us
$detect = new Mobile_Detect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
$scriptVersion = $detect->getScriptVersion();
// Check to see if we are already logged in under an already validated account
if(isset($_COOKIE['AGMARDTuid']) || isset($_COOKIE['AGMARDTtoken'])) {
logout();
header("Location: ../");
exit;
} else {
$val = base64url_decode($_GET['val']);
$val = explode(":-:", $val);
$uid = $val[0];
$add = $val[1];
$key = $val[2];
// These are the three items that are pulled out of the URL $val value. This works fine
// It's only here to check it's working ok for the moment
echo "uid: ".$uid."<br>add: ".$add."<br>key: ".$key."<br><br>";
// Kill the process if either of the three values - $uid, $add, $key - are empty
if(($uid == "") || ($uid == NULL) || ($add == "") || ($add == NULL) || ($key == "") || ($key == NULL)) {
logout();
header("Location: ../");
exit;
} else {
// Seems everything is in order for email validation, so lets validate
$yes = "yes";
$NULL = NULL;
try {
$stmt = $conn->prepare("UPDATE $database.users SET `emailValidated` = :validate, `emailValidationKey` = :newkey WHERE `uid` = :uid AND `email` = :add AND `emailValidationKey` = :key");
$stmt->bindParam(':uid', $uid);
$stmt->bindparam(':add', $add);
$stmt->bindParam(':key', $key);
$stmt->bindParam(':validate', $yes);
$stmt->bindParam(':newkey', $NULL);
$stmt->execute();
$result = "success";
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); $result = "fail"; }
$conn = null;
echo "result: ".$result." (post sql)<br><br>";
if($result == "fail") {
echo "Email did not successfully validate, there was a problem<br><br>";
echo $conn . "<br>" . $e->getMessage();
} else if($result == "success"){
echo "Email successfully validated<br><br>";
echo $conn . "<br>" . $e->getMessage();
}
echo "<br><br>We got to the end!";
}
}
?>
The code works, kinda. The problem is, if there is NOT an account within the database that matches all three values passed to the script from the URL, it still displays as having updated (validated) an account, even though it has not. Why is this?
Also, for the section that I am binding some parameters, specifically these two:
$stmt->bindParam(':validate', $yes);
$stmt->bindParam(':newkey', $NULL);
Why do I seem to have to assign $yes = "yes"; and "$NULL = NULL; as variables beforehand? I did try:
$stmt->bindParam(':validate', 'yes');
$stmt->bindParam(':newkey', NULL);
and
$stmt->bindParam(':validate', yes);
$stmt->bindParam(':newkey', NULL);
and
$stmt->bindParam(':validate', 'yes');
$stmt->bindParam(':newkey', 'NULL');
all without success.
Answers and info and suggestions always welcome and appreciated. Thank you!
C
You should use bindValue instead bindParam when you want to pass a value (or the result of a function) in the prepared statement.
$id = 100;
$datas = array('a', 'b', 'c');
$stmt = $db->prepare("SELECT * FROM user WHERE id = :id AND status > :status AND justForExample = :other");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindValue(':status', 1, PDO::PARAM_INT);
$stmt->bindValue(':other', implode("", $datas), PDO::PARAM_STR);
$stmt->execute();
The documentation to BindValue
The documentation to BindParam
More informations about the difference

$mysqli variable works on Server but not on localhost

On my server I include 'config.php' in each function and it works perfectly, however when I do the same on my LOCALHOST the variable $mysqli cannot be found, will the PHP version differ from server to localhost? The paths are both 100% correct.
The error is as follows;
Notice: Undefined variable: mysqli in
C:\Users\PC\Documents\XAMPP\htdocs\php\myfunctions.php on line 20
config.php
$mysqli = new mysqli('localhost', 'userone', 'password', 'iitb');
The connection obviously changes when I use server
myfunctions.php
<?php
class News
{
function getLatest()
{
include 'config.php'; // WHERE TO PUT THIS CANNOT FIND MYSQL
$time = date('Y-m-d G:i:s', strtotime("-1 week"));
$stmt = $mysqli->prepare("SELECT ForumId, ForumTitle, ForumPostText FROM `forum` WHERE `PostDate` > ? ORDER BY PostDate desc LIMIT 5 ");
$stmt->bind_param('s', $time);
$stmt->execute();
$stmt->bind_result($ForumId, $ForumTitle, $ForumPostText);
$stmt->store_result();
if ($stmt->num_rows() == 0) {
echo "<p>No latest article available</p>";
} else {
while ($row = $stmt->fetch()) {
echo '<p class="posttitle">' . $ForumTitle . ' </p>';
echo '<p class="posttext">' . substr($ForumPostText, 0, 93) . ' ...</p>';
}
$stmt->free_result();
}
}
function mostPopular()
{
include 'config.php'; // WHERE TO PUT THIS CANNOT FIND MYSQL
$stmt = $mysqli->prepare("SELECT ForumId, ForumTitle, ForumPostText FROM forum ORDER BY Views DESC LIMIT 5");
$stmt->execute();
$stmt->bind_result($ForumId, $ForumTitle, $ForumPostText);
$stmt->store_result();
if ($stmt->num_rows() == 0) {
echo "<p>No latest article available</p>";
} else {
while ($row = $stmt->fetch()) {
echo '<p class="posttitle">' . $ForumTitle . ' </p>';
echo '<p class="posttext">' . substr($ForumPostText, 0, 93) . ' ...</p>';
}
$stmt->free_result();
}
}
}
Rather than having include 'config.php'; // WHERE TO PUT THIS CANNOT FIND MYSQL in each of your functions, add the $database parameter Eg function mostPopular($database){... and change $mysqli-> to $database->
Then when you call the functions, pass the database through mostPopular($database)
On an unrelated note: You may also find it easier to have the functions return an array rather than echo HTML so that your functions just get the data format it and return values. (It also means you can get away from echoing full HTML.
Here is an example using your mostPopular function
Function:
function mostPopular($databaseName){
$stmt = $mysqli->prepare("SELECT ForumId, ForumTitle, ForumPostText FROM forum ORDER BY Views DESC LIMIT 5");
$stmt->execute();
$stmt->bind_result($ForumId,$ForumTitle,$ForumPostText);
$stmt->store_result();
$returnData = array();
if($stmt->num_rows() > 0){
$i = 0;
while($row = $stmt->fetch()){
$returnData[$i]['ForumId'] = $ForumId;
$returnData[$i]['ForumTitle'] = $ForumTitle;
$returnData[$i]['ForumPostText'] = substr($ForumPostText, 0,93) . ' ...';
++$i;
}
$stmt->free_result();
}
}
return $returnData;
}
Use:
<div id="mostPopular">
<?php
$mostPopular = mostPopular($mysqli);
if(count($mostPopular) === 0){
?>
<p>No latest article available</p>
<?php
} else {
foreach($mostPopular as $Popular){
?>
<p class="posttitle"><?php echo $Popular['ForumTitle'];?></p>
<p class="posttext"><?php echo $Popular['ForumPostText'];?></p>
<?php
}
}
?>
</div>
The problem is that the config.php script is not started with the PHP start tag of
<?php
The config file should be like this:
<?php
$mysqli = new mysqli('localhost', 'userone', 'password', 'iitb');
EDIT: Make sure also to check the php_short_tags. It could be that the config.php file starts with a short tag <? and the short_open_tag is disabled on your localhost server.

Categories