When the value is not found no message is shown - php

I have the following example database:
rfidtags` (`name`, `id`, `gender`, `email`, `mobile`) VALUES
('Alsan', '39EAB06D', 'Male', 'mydigitalnepal#gmail.com', '9800998787'),
('John', '769174F8', 'Male', 'john#email.com', '23456789'),
('Thvhm,b', '81A3DC79', 'Female', 'jgkhkkmanjil#gmail.com', '45768767564'),
And the following code:
<?php
$mysql_host = 'localhost';
$mysql_port = '';
$mysql_user = 'user';
$mysql_pass = 'password';
$mysql_mydb = 'rfidcards';
$con = new mysqli($mysql_host, $mysql_user, $mysql_pass, $mysql_mydb );
if ($con -> connect_errno) {
echo "Failed to connect to MySQL: " . $con -> connect_error;
exit(2);
}
//$tagid = '39EAB06D';
$tagid = 'CCCCCCCC';
$query = "SELECT name, id FROM rfidtags WHERE id = '$tagid'";
if ($stmt = $con->prepare($query)) {
$stmt->execute();
$stmt->bind_result($name, $id);
$stmt->fetch();
// debug init
//var_dump($stmt);
// debug end
echo "$name $id\n";
$stmt->close();
} else {
echo "failed to fetch data\n";
}
$con->close();
Tags
tagid = '39EAB06D'
and
tagid = 'CCCCCCCC'
are for testing purposes.
When the first is selected, the ressult is shown, but when the second (non existant on the database) is selected, a blank line is shown, instead of "failed to fetch data"

Your echo "failed to fetch data\n"; is in the wrong place. $con->prepare($query) will only return false if there was something wrong in preparing the statement not if the statement returned no entries.
You would want to do the if check on your fetch like:
if($stmt->fetch()) {
echo "$name $id\n";
} else {
echo "No result returned";
}

mysqli::prepare() does not fail when the query returns zero records. In fact, it's a rather bad practice to check if prepare succeeded or not.
Your code would be much easier if you used PDO instead of mysqli, but if you are willing to suffer with mysqli then the right code to do this kind of thing would be:
<?php
$mysql_host = 'localhost';
$mysql_port = '';
$mysql_user = 'user';
$mysql_pass = 'password';
$mysql_mydb = 'rfidcards';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli($mysql_host, $mysql_user, $mysql_pass, $mysql_mydb);
$con->set_charset('utf8mb4'); // always set the charset
//$tagid = '39EAB06D';
$tagid = 'CCCCCCCC';
$query = "SELECT name, id FROM rfidtags WHERE id = ?";
$stmt = $con->prepare($query);
$stmt->bind_param('s', $tagid);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($name, $id);
if ($stmt->fetch()) {
echo "$name $id\n";
} else {
echo "failed to fetch data\n";
}

It's wrong because mysqli::prepare() return mysqli_stmt or false.
Generaly, it return false only when you have a wrong SQL query.
But in your case, you have a correct SQL query even if the id you request does not exist in the table.
So you need to check the results after executing stmt but not the stmt before executing.

Related

How to expand my PHP code to add more database fields?

I found a code php for updating database, but it's just for two field that's id and item. How about if I have 7 fields, that's id_admin, name, email, address, phonenumber, username, and password, and the table name is admin. This the code that I found.
<?php
error_reporting(0);
include("db_config.php");
// array for JSON response
$response = array();
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$result = mysql_query("update myorder set item='$item' where id='$id' ") or die(mysql_error());
$row_count = mysql_affected_rows();
if($row_count>0){
$response["success"] = 1;
$response["message"] = "Updated Sucessfully.";
}
else{
$response["success"] = 0;
$response["message"] = "Failed To Update.";
}
// echoing JSON response
echo json_encode($response); } ?>
Change these lines :
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$result = mysql_query("update myorder set item='$item' where id='$id' ") or die(mysql_error());
with these :
if( isset($_POST['submit'] ) ) {
$id=htmlspecialchars($_POST['id']);
$item=htmlspecialchars($_POST['item']);
$name=htmlspecialchars($_POST['name']);
$email=htmlspecialchars($_POST['email']);
//and so on...
$result = mysql_query("update myorder set item=$item, name=$name, email= $email ... where id=$id ") or die(mysql_error());
Warning mysql_query, mysql_fetch_array,mysql_connect etc.. extensions were deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0.
Instead, the MySQLi or PDO_MySQL extension should be used.
<?php
error_reporting(0);
//db connection
global $conn;
$servername = "localhost"; //host name
$username = "username"; //username
$password = "password"; //password
$mysql_database = "dbname"; //database name
//mysqli prepared statement
$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());
mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");
// array for JSON response
$response = array();
if( isset($_POST['id'] ) && isset($_POST['item']) ) {
$id=$_POST['id'];
$item=$_POST['item'];
$stmt = $conn->prepare("update myorder set item=?,name=?,id_admin=?,email=?,address=?,phonenumber=? where id=? ");
$stmt->bind_param('ssissii',$item,$name,$id_admin,$email,$address,$phonenumber,$id);
The argument may be one of four types:
i - integer
d - double
s - string
b - BLOB
//change it by respectively
$stmt->execute();
$row_count= $stmt->affected_rows;
if($row_count>0)
{
$response["success"] = 1;
$response["message"] = "Updated Sucessfully.";
}
else{
$response["success"] = 0;
$response["message"] = "Failed To Update.";
}
// echoing JSON response
echo json_encode($response);
$stmt->close();
$conn->close();
}
?>
Always use parameterized queries when user value needs to be inserted in query.
Example:
$statement = $conn->prepare("update admin set name=?, email=?, address=?, phonenumber=?, username=?, password=? WHERE id_admin=?");
$statement->bind_param('ssssssi', $name, $email, $address, $phonenumber, $username, $password, $id_admin);
$statement->execute();

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo 'Connected successfully';
}
catch(PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

Switch from mysql_connect to PDO: mysql_num_rows() expects parameter 1 to be resource

I had code that used mysql_connect which I understand is now deprecated to I switched to the following code (I'm working locally):
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$DBusername = 'admin';
/*** mysql password ***/
$DBpassword = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
/*** echo a message saying we have connected ***/
echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
But this now means that a function of mine breaks:
$result = mysql_num_rows($query);
Because, following the script back, the connection is not working. There is something up with my PDO connection script but I do not understand what I have done wrong. The details are correct for logging into phpMyAdmin on localhost.
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
PDO is entirely independent from the mysql extension, you will have to update your function calls as well. mysql_query for example should be a combination of prepare and execute.
As a note: Please please use Prepared Statements, your example query is completely insecure.
As an example was requested:
// initialize PDO
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $DBusername, $DBpassword);
// Prepare a query
$sql = "SELECT COUNT(*) AS count
FROM users
WHERE username = ?
LIMIT 1";
$statement = $dbh->prepare($sql);
// execute the query
$statement->execute(array($username));
// retrieve the first row
$row = $statement->fetch();
if ($row['count']) echo 'The user exists';
else echo 'The user does not exist';

PHP PDO MySQL get entries from Access and INSERT into MySQL

My goal here is to replicate a local MS Access database into my MySQL database (using php PDO)
The MS Access database is located on a network shared drive and updates itself with new entries every 6 hours.
In the code below I retrieved the max id number from MySQL table 'production_schedule', then I made an ODBC connection to retrieve all entries from MS ACCESS database that are greater than the max id number.
But now I cannot figure out how to insert these new entries into the MySQL table 'production_schedule'.
Can anyone please help?
<?php
/*USING XAMPP*/
$dsn = "mysql:host=localhost;dbname=qmsdb;charset=utf8";
$uname = "root";
$pword = "";
$db = null;
$limit = 10;
$counter = 0;
while (true) {
try {
$db = new PDO($dsn, $uname, $pword);
$db->exec( "SET CHARACTER SET utf8" );
$db->setAttribute( PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC );
$db->setAttribute( PDO::ATTR_PERSISTENT, true );
break;
}
catch (Exception $e) {
$db = null;
$counter++;
if ($counter == $limit)
throw $e;
}
}
$aid = $db->prepare("SELECT MAX(id) FROM production_schedule");
$aid->execute();
$big_id = $aid->fetchColumn();
$refid = intval($big_id);
$conn=odbc_connect('Prod_Schedule','','');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT * FROM Schedule WHERE ID > $refid";
$rs=odbc_exec($conn,$sql);
if (!$rs) {
exit("Error in SQL");
}
***** INSERT CODE TO PUT THESE MS ACCESS ENTRIES INTO THE MYSQL TABLE ******
?>
something like this maybe:
while(odbc_fetch_row($rs)){
$sql = "INSERT INTO production_schedule (fieldName1, fieldName2, fieldName3) VALUES (?, ?, ?)";
$stmt = $dbh->prepare($sql);
for($i=1;$i<=odbc_num_fields($rs);$i++){
$stmt->bindValue($i, odbc_result($rs,$i));
}
$stmt->execute();
}
Note: depends on how many data you have to dump, you should use a solution like this: PDO Prepared Inserts multiple rows in single query to reduce risk of PHP timeout.
I just tested the following code and it seems to work okay for me:
$dsn = "mysql:host=localhost;port=3307;dbname=myDb;charset=utf8";
$uname = "root";
$pword = "whatever";
$mysqlDb = new PDO($dsn, $uname, $pword);
$mysqlDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$mysqlSql = "INSERT INTO clients (LastName, FirstName) VALUES (?, ?)";
$mysqlCmd = $mysqlDb->prepare($mysqlSql);
$LastName = '';
$FirstName = '';
$mysqlCmd->bindParam(1, $LastName, PDO::PARAM_STR, 255);
$mysqlCmd->bindParam(2, $FirstName, PDO::PARAM_STR, 255);
$connStr =
'Driver={Microsoft Access Driver (*.mdb, *.accdb)};' .
'Dbq=C:\\Users\\Public\\Database1.accdb;';
$accessDb = odbc_connect($connStr, "", "");
$accessSql = "SELECT LastName, FirstName FROM Clients";
$accessResult = odbc_exec($accessDb, $accessSql);
while ($accessData = odbc_fetch_array($accessResult)) {
$LastName = $accessData["LastName"];
$FirstName = $accessData["FirstName"];
$mysqlCmd->execute();
}
First create a function to insert the values into MySQL, then loop through the ODBC results;
function createProductionSchedule($company,$person,$order){
$mysqli_con=mysqli_connect(DBHOST,DBUSER,DBPASS,DBNAME);
if (mysqli_connect_errno($mysqli_con))
{
echo 'Failed to connect to MySQL';
}
//Obviously your own fields here
$company = mysqli_real_escape_string($mysqli_con, $company);
$person = mysqli_real_escape_string($mysqli_con, $person);
$order = mysqli_real_escape_string($mysqli_con, $order);
$sql = "INSERT INTO production_schedule VALUES ('$company','$person','$order')";
mysqli_query($mysqli_con, $sql);
return mysqli_insert_id($mysqli_con);
mysqli_close($mysqli_con);
}
Then in your code section
while (odbc_fetch_row($rs))
{
$company=odbc_result($rs,"Company");
$person=odbc_result($rs,"Person");
$order=odbc_result($rs,"Order");
//Call the function to insert the record
createProductionSchedule($company,$person,$order);
}
odbc_close($conn);

How to fetch assoc array while using mysqli prepare

To make sure my database is secure I'm using prepare statements. Here is my code:
//connecting to MySql database
$con=mysqli_connect("host","user","pass","dbname");
// checking database connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_prepare($con,"SELECT * FROM `table` WHERE emb=? LIMIT 1");
mysqli_stmt_bind_param($stmt, 's', $emb);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
Now I want to know how can I use ASSOC fetch array
$embInfo = mysqli_fetch_array($stmt, MYSQLI_ASSOC);
I want this so that I can just put something like below to get values
$embInfo['name']
and
$embInfo['email']
try this:
//connecting to MySql database
$con=mysqli_connect("host","user","pass","dbname");
// checking database connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$stmt = mysqli_prepare($con,"SELECT * FROM `table` WHERE emb=? LIMIT 1");
mysqli_stmt_bind_param($stmt, 's', $emb);
mysqli_stmt_execute($stmt);
while($embInfo = mysqli_fetch_array($stmt, MYSQLI_ASSOC)){
echo 'My name is '.$embInfo['name'].'and my email is '.$embInfo['email'].'<br/>';
}
mysqli_stmt_close($stmt);
May i suggest an alternative
{
$server = '';
$user = '';
$pass = '';
$db = '';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
// show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);
$club=$_POST'club'];
$sql = "SELECT * FROM players WHERE club = '$club'";
$result=mysqli_query($mysqli,$sql);
while($row = mysqli_fetch_array($result))
{
echo $row['player'];
}
}

Categories