Problems with my first prepared MySQLi - php

Following a question earlier about sanitising a string, I'm now attempting to use the principles seen at How can I prevent SQL injection in PHP?
$connection = mysqli_connect('localhost', 'user', 'xxxxx');
$database = mysqli_select_db($connection, 'xxxxx');
$param1 = $_GET['q'];
//prepared mysqli statement
$stmt = mysqli_stmt_init($connection);
$stmt = $connection->prepare('SELECT * FROM CONTACTS WHERE SURNAME = ?');
$stmt->bind_param('s', $param1); // 's' specifies the variable type => 'string'
$stmt->execute();
$result = $stmt->get_result();
$num_rows = mysqli_num_rows($result);
echo "Records Found:".$num_rows."<br/><br/><hr/>";
while ($row = $result->fetch_assoc()) {
echo $result['COMPANY']." ".$result['FORENAME']." ".$result['SURNAME'];
}
However, although $connection and $database are both processing correctly, I'm getting the following error:
Fatal error: Call to undefined method mysqli_stmt::get_result() in
/my_first_mysqli.php on line xxxx
Am I not getting the syntax correct or does it have more to do with the php version 5.2.0 I'm rocking. (Yes, I'm upgrading code before upgrading server).
If it's the latter, is there a simpler MySQLi method I can use that will work before I upgrade the php version?
EDIT
I've updated this now which is a bit cleaner:
$servername = "localhost"; $username = "xxxx"; $password = "xxxx"; $dbname = "xxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$param1 = $_GET['q'];
$stmt = mysqli_prepare($conn, "SELECT CONTACTID, COMPANY, FORENAME, SURNAME FROM CONTACTS WHERE SURNAME = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $param1);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $CONTACTID, $COMPANY, $FORENAME, $SURNAME);
/* fetch value */
mysqli_stmt_fetch($stmt);
$num_rows = mysqli_num_rows($stmt);
echo "Records Found:".$num_rows."<br/><br/><hr/>";
/* close statement */
mysqli_stmt_close($stmt);
mysqli_close ($conn);
I'm obviously not getting a recordset result to loop through and don't know how to... The rest appears to work without throwing an error.

Thanks for all the contributions. I now have a working procedural solution that I thought I'd post for reference.
It's a bit cumbersome but it's fine and I believe it follows good modern practice.
$servername = "localhost"; $username = "xxxx"; $password = "xxxx"; $dbname = "xxxx";
$conn = new mysqli($servername, $username, $password, $dbname);// Create connection
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$param1 = $_GET['q'];
$stmt = mysqli_prepare($conn, "SELECT CONTACTID, COMPANY, FORENAME, SURNAME FROM CONTACTS WHERE SURNAME = ?");
mysqli_stmt_bind_param($stmt, "s", $param1);// bind parameters for markers
mysqli_stmt_execute($stmt);// execute query
mysqli_stmt_bind_result($stmt, $CONTACTID, $COMPANY, $FORENAME, $SURNAME);// bind result variables
// fetch values
while (mysqli_stmt_fetch($stmt)) {
echo $CONTACTID."<br>";
echo $COMPANY."<br>";
echo $FORENAME."<br>";
echo $SURNAME."<br>";
echo "<hr/>";
}
mysqli_stmt_close($stmt);// close statement
mysqli_close ($conn);
Feedback welcome if you can see any improvements.

Related

Getting error when calling connect as function in prepare statement

EDIT. My error ONLY occurs when calling database connection as a function, if I call my database connection normally, the error do not occur.
I'm trying to execute a prepare statement with database connection as a function so that it can be reused inside other functions. Executing normal SQL codes work when using database connection function but I'm getting errors when I try to use in a prepare statement.
This is my code.
function connect(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
if (connect()->connect_error) {
die("Connection failed: " . connect()->connect_error);
} else {
echo "GOOD";
}
$val = "1";
$stmt = connect()->prepare("SELECT * FROM countries WHERE id = ?");
$stmt->bind_param("s",$val);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['name'];
}
$stmt->close();
When connecting database as a normal variable such as this works.
$stmt = $conn->prepare("SELECT * FROM countries WHERE id = ?");
However, I get "Call to a member function fetch_assoc() on bool" whenever I tried to call my connection as a function.
What am I doing wrong with this code?
After searching for a while and based on this answer, I was able fix my problem by declaring a variable for connection. However, this doesn't explain why directly calling connect doesn't work. Can somebody explain to me why the first way doesn't work?
$db = connect();
$stmt = $db->prepare("SELECT * FROM countries WHERE id = ?");

Get sum of row where username is the current user's name

This code just displays a blank webpage. Is there anything wrong with it? It is supposed to show the total points the logged in user has.
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "randompassword";
$dbname = "transactions";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT sum(points) AS points FROM transaction WHERE username = '".mysqli_real_escape_string($conn,$_SESSION['username'])."'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
print($row)
?>
You should enable the error_reporting like this
error_reporting(E_ALL);
ini_set("display_errors", 1);
transaction is a keyword in mysql. So use back tick ( ` ).
Instead of using direct substitution values, you could use below methods to avoid sql injection.
Using MySQLi (for MySQL):
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
Please refer How can I prevent SQL-injection in PHP?

select an attribute in mysql, php

I just start to learn about phpMyAdmin and mysql. here's a question: I want to select something in my "student" table and it echo the result. but as I checked it returns 0 row for the search. but I have it in my database.
here is my code:
$conn = new mysqli($servername, $username, $password, $dbname);
$params="#name varchar(30)";
$paramslist="#name='$name%";
$sql = "SELECT name,address,city,birthday FROM student WHERE NAME=#NAME";
$dbsql = "EXEC sp_executesql
N'$sql',
N'$params',
$paramslist";
$result = $conn->query($sql);
ECHO $result->num_rows;
I don't know what is the problem. thank you for helping.
$sql = "SELECT name,address,city,birthday FROM student WHERE name=".$name;
$result = $conn->query($sql);
echo $result->num_rows();
this is what works for me with prepared statement
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name='Veshraj Joshi';
$stmt = $conn->prepare("SELECT name,address,city,birthday FROM student WHERE NAME=?");
/* bind parameters for markers */
$stmt->bind_param("s", $name);
/* execute query */
$stmt->execute();
$result = $stmt->get_result();
/* now you can fetch the results into an array */
while ($student = $result->fetch_assoc()) {
// use your $student array as you would with any other fetch
echo $student['address'].'<br>';
}
The following uses prepared statements. You should always use prepared statements when including user input to safeguard for SQL Injection attacks.
Every time fetch() executes, the results are bound to the variables specified by bind_result()
$conn = new mysqli($servername, $username, $password, $dbname);
$query = "SELECT name,address,city,birthday FROM student WHERE name=?";
$stmt = $conn->prepare($query);
$searchTerm = "%$name%";
$stmt->bind_param('s', $searchTerm);
$stmt->execute();
$stmt->bind_result($resultName, $resultAddress, $resultCity, $resultBirthday);
while($stmt->fetch())
{
echo $resultName . " " . $resultAddress . " " . $resultCity . "<br/>";
}

PHP Prepared Statement/Bind Param Code Crashing

Can someone explain why this gives me a 500 internal server error? I tried adding some sql injection protection and I'm not sure what I'm doing wrong. Should I be doing this in an object oriented style instead of procedural?
<?php
$conn = mysqli_connect($host, $user, $pwd)or die("Error connecting to database.");
mysqli_select_db($conn, $db) or die("Couldn't select the database.");
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = mysqli_stmt_init($conn);
$query = "SELECT * FROM Users WHERE email=? AND password=?";
mysqli_stmt_prepare($stmt, $query) or die("Failed to prepare statement.");
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_num_rows($result);
if($count == 1){
//Log in successful
}
else {
//Wrong Username or Password
}
mysqli_close($conn);
?>
mysqli_stmt_get_result is available in PHP 5.3, but I am running 5.1. Also, the mysqlnd driver must be installed for this call to work.
For more information, see Call to undefined method mysqli_stmt::get_result

Issue inserting data using mysqli in MySQL

I try to use mysqli in order to insert data in my database. But does not work. Where may be the error?
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statment = $myDb->prepare("INSERT INTO user(name,surname,age)
VALUES (?,?,?)");
$statement->bind_param('s', $_POST['name']);
$statement->bind_param('s', $_POST['surname']);
$statement->bind_param('i', 25);
$statement->execute();
$statement->free_result();
EDIT:
I obtain this error:
Binding parameters failed: (0) Execute failed: (2031) No data supplied for parameters in prepared statement
You've got the error here:
$statement->bind_param('i', 25);
25 is not a variable. You can only use variables when binding parameters. You can't use constants nor fixed strings or numbers when binding.
Besides, it never worked for me to split the parameters when binding. I got an error. I need to do so:
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statement = $myDb->prepare("INSERT INTO user (name,surname,age) VALUES (?,?,25)");
$statement->bind_param('ss', $_POST['name'], $_POST['surname']);
$statement->execute();
$statement->free_result();
$statement->close();
I solved the problem using a correct bind of parameter. Here the correct code:
$myDb = new mysqli($hostname, $username, $password, $database);
if($myDb->connect_errno > 0){
die('Unable to connect to database [' . $myDb->connect_error . ']');
}
$statment = $myDb->prepare("INSERT INTO user(name,surname,age)
VALUES (?,?,?)");
$statement->bind_param('s', $name);
$statement->bind_param('s', $surname);
$statement->bind_param('i', $age);
$name = $_POST['name'];
$surname = $_POST['surname'];
$age = 25;
$statement->execute();
$statement->free_result();

Categories