How to fetch assoc array while using mysqli prepare - php

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'];
}
}

Related

When the value is not found no message is shown

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.

How do I display data using the url

How do I display the information data using the ID in the url
example is www.thatsite.com/?id=1092
and it will display the data of the 1092 ID
<?php
$connect = mysqli_connect("localhost", "xxxxxxx", "xxxx","xxxx");
$query = "SELECT `name`, `age`, `xxxxx` , `xxxxx`, `image` FROM `profiles` WHERE `id` = $id LIMIT 1";
$id=$_GET['id'];
$result = mysqli_query($connect, $query,$id);
while ($row = mysqli_fetch_array($result))
{
echo $row['name'];
echo $row['xxxx'];x
echo $row['age'];
echo $row['xxxxxxx'];
echo $row['image'];
}
?>
Your code is full of security holes. It is prone to sql injection, xss attack, csrf, html injection.
I have re-written it to circumvent all the issues.
1.) Sql Injection is now mitigated using prepare queries
2.) Html injection is mitigated using intval for integer variables and strip_tags for strings. you can read more about data validations and sanitization in php to see more options available
3.) xss attack has been mitigated via htmlentities().
you can also use htmlspecialchars(). Read more about all this things
see better secured codes below
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ur dbname";
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
// ensure that the Id is integer using intval
$id = intval($_GET["id"]);
// if id is a string. you can strip all html elements using strip_tags
//$id = strip_tags($_GET["id"]);
//Avoid sql injection using prepared statement
// prepare and bind
$stmt = $connect->prepare("SELECT name, age , xxxxx, image FROM profiles WHERE id = ? LIMIT 1");
// id is integer or number use i parameter
$stmt->bind_param("i", $id);
// id is integer or number use s parameter
//$stmt->bind_param("s", $id);
$stmt->execute();
$stmt -> store_result();
$stmt -> bind_result($name, $age, $xxxxx, $image);
while ($stmt -> fetch()) {
// ensure that xss attack is not possible using htmlentities
echo "your Name: .htmlentities($name). <br>";
echo "your age: .htmlentities($age). <br>";
echo "your xxxxx: .htmlentities($). <br>";
echo "your image name: .htmlentities($image). <br>";
}
$stmt->close();
$connect->close();
?>
from https://www.w3schools.com/php/php_mysql_select.asp
leave out the 'get id', the id is in the SQL:
$id=$_GET['id'];
The similar example at
https://www.w3schools.com/php/php_mysql_select.asp
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);

mysqli statement does not work under php

There's a bit problem for mysqli select statement as I did a select statement which actually counts the number of results. But it does not return the value I want but instead it returns none. Need help guys. I did this select statement as a function using mysqli and php
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
echo "string</br>";
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['userssss']."asdasd</br>";
die("userssss");
$return = $row['user'];
return $return;
}
result
string
asdasd
userssss
It should show the result before asdasd
add global $con;
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as user from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['user'][0]."asdasd";
die();
$return = $row['user'][0];
return $return;
}
I found it. Silly of me.
Instead of using assoc, one must use array
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$return = $row['user'];
return $return;
}
You need to count everything meaning rows matched where clause. Also try to adopt prepared statements. Bellow code works.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
function count_result($data){
$user = 'username';
$password = 'password';
$db = 'database';
$host = 'hostname';
$port = 3306;
/* Attempt MySQL server connection. Assuming you are running MySQL server */
$link = mysqli_connect($host, $user, $password, $db);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if($stmt = $link -> prepare("SELECT COUNT(*) FROM test WHERE ID= ?"))
{
/* Bind parameters, s - string, b - blob, i - int, etc */
$stmt -> bind_param("i", $data);
$stmt -> execute();
/* Bind results */
$stmt -> bind_result($testfield1);
/* Fetch the value */
$stmt -> fetch();
$numberofrows = $stmt->num_rows;
} else{
echo "ERROR: Could not able to execute SQL. " . mysqli_error($link);
}
/* Close statement */
$stmt -> close();
echo '# rows: '. $numberofrows . PHP_EOL;
echo 'Count = '. $testfield1 ;
}
count_result(24);
?>
A silly mistake in your code :
function count_result($data){
global $con;
$sql = "SELECT count(user_id) as userssss from credentials where user_id = '$data'";
$result = mysqli_query($con,$sql) or die('userssss');
echo "string</br>";
$row = mysqli_fetch_assoc($result,MYSQLI_ASSOC);
echo $row['user']."asdasd</br>"; // did changes on this line
die("userssss");
$return = $row['user'];
return $return;
}

Why do I encounter Internal Server Error while converting MySql TO MySQLi?

I've tried searching for answers and used some tutorials, but nothing
has helped.
I can successfully establish a connection to my database.
But when I try to run this query, I get 500-Internal Server Error.
The code I am using is:
$stmt = $conn->prepare("SELECT * FROM people WHERE name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows):
$row = $stmt->fetch_assoc();
$id = $row['id'];
$position = $row['position'];
else:
die("User not found.");
endif;
How I used to do it using MySQL:
$sql = "SELECT * FROM people WHERE name = '$name'";
$result = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($result) > 0):
$row = mysql_fetch_array($result);
$id = $row['id'];
$position = $row['position'];
else:
die("User not found.");
endif;
Any and all help will be appreciated.
EDIT: The following code is at the start of my file:
// Connection Details
$host = "";
$user = "";
$pass = "";
$db = "";
// Database Connection
$conn = new mysqli($host, $user, $pass, $db);
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
Could you please tell me the best way to replicate the MySQL code I posted in MySQLi?

Filter results by date in timestamp field

I have already had some help but not sure why this isn't working.
I am trying to use a form to let a user filter their activity (which is stored in a DB)
My code:
$_GET['from'] = '01/11/2013';
$_GET['to'] = '25/11/2013';
$from = DateTime::createFromFormat('d/m/Y', $_GET['from']);
$to = DateTime::createFromFormat('d/m/Y', $_GET['to']);
$sql = "
SELECT * FROM transfer
WHERE personID = $user AND DATE(time) BETWEEN '%s' AND '%s'
";
$sql = sprintf($sql, $from->format('Y-m-d'), $to->format('Y-m-d'));
print_r($sql);
This prints
SELECT * FROM transfer WHERE personID = 84587749 AND DATE(time) BETWEEN '2013-11-01' AND '2013-11-14'
When I query this in PHPmyadmin it shows the record, however not showing in my page?
The SQL looks fine but you don't appear to have issued the executed the SQL query in the database and retrieved the results?? Maybe I'm missing something but you need to connect to your database:
class DBi {
public static $mysqli;
}
DBi::$mysqli = new mysqli('servername', 'database', 'password', 'user');
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
Then you need to perform the query:
$result = DBi::$mysqli->query($sql) or die ("Unable to execute SQL command:".$sql);
And finally, retrieve and use the result:
$row = $result->fetch_assoc();
echo $row["fieldname"];
Here is an example how you print out your results.
$dbserver = "localhost";
$dbname = "nameofDB";
$dbusername = "username";
$dbpassword = "password";
$mysqli = new mysqli($dbserver, $dbusername, $dbpassword, $dbname);
$query = "SELECT * FROM transfer WHERE personID = 84587749 AND DATE(time) BETWEEN ? AND ?";
if($stmt = $mysqli->prepare($query)){
/*
Binds variables to prepared statement
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
*/
$to = $_POST['to'];
$from = $_POST['from'];
$stmt->bind_param('ss', $from, $to);
/* execute query */
$stmt->execute();
/* Get the result */
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Configure this how you want to print out each row.
echo 'Details: '.$row['details'].'<br>';
echo 'Time: '.$row['time'].'<br>';
echo 'Balance: '.$row['balance'].'<br>';
echo '<br><br>';
}
/* free results */
$stmt->free_result();
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();

Categories