Getting error when calling connect as function in prepare statement - php

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 = ?");

Related

Problems with my first prepared MySQLi

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.

How to check whether mysql update query is successful or not?

function insertNewBidPrice($code, $newBidPrice)
{
global $conn;
$sql = "update auctionitem set highestbid=$newBidPrice where code=$code";
//echo $sql;
if($conn->query($sql))
{
return 1;
}
else
{
require 0;
}
}
I have this php fuction that results 0 all time although update query successfully update the table.
I use PDO.
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Create a statement object first, using prepare.
$stmt = $conn->prepare($sql);
$worked = $stmt->execute();
if ($worked == TRUE) {
//I did stuff
} else {
// nope
}
function insertNewBidPrice($code, $newBidPrice) {
global $conn;
// write your query
$sql = "UPDATE auctionitem SET highestbid='$newBidPrice' WHERE code='$code'";
// run the query
$result = $conn->query($sql);
// check the result of the query
if ($result == true) {
// it was a success
return 1;
} else {
return 0;
}
}
global $conn;
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
// it worked
}
Here you go this should do the trick. I noticed you say "require 0" in your if else statement it needs to be a return. Other then that i'm not sure on your problem but there are 2 possibilities i can think of.
Your $conn variable is invalid. Check it has the correct credentials, see the $conn->connect_error line, it is in the code i wrote but also here: http://php.net/manual/en/mysqli.connect-error.php.
Possibly the query incorrect. Personally i format everything with capitals ect. as my text editor colors it when i do that and it is easy for me to see what is what. Also there were no quotes surrounding the variables in your SQL statement, this is fine if it is an integer but if you are accidentally passing a string it will fail.
Also check that you have selected the correct table ect. in your SQL.

unable to update SQL table with php program

I have installed XAMPP and ensured that all the servers are running. I'm completely new to PHP and SQL
I configured a local database called test and a table called sensor.
I have added a user called arduino with a password.
pls ignore the comments
<?php
// Prepare variables for database connection
$dbusername = "arduino";
$dbpassword = "xxx";
$server = "localhost";
// Connect to your database
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
// Prepare the SQL statement
$sql = "INSERT INTO test.sensor (value) VALUES ('".$_GET["value"]."')";
// Execute SQL statement
// mysql_query($sql);
?>
I want to use this set up to fetch data from arduino. Before connecting this set up to arduino, I wanted to ensure that this would be able to fetch data by passing http://localhost/write_data.php?value=100 to the browser. I was expecting that this would update the table with id, timestamp and value (of 100). It did not.
I had trouble with $dbconnect = mysql_pconnect($server, $dbusername, $dbpassword); and hence replaced that with $db = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
I also had trouble with mysql_query($sql);. So I have commented it out for now.
How can I get this to work? Where can I find easy to follow documentation for MySql replacements?
Updated Code based on answers
<?php
$dbusername = "arduino";
$dbpassword = "test";
$server = "localhost";
$dbconnect = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'arduino', 'test');
$stmt = $dbconnect->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
print "procedure returned $return_value\n";
?>
Brother checkout this example.. you have to bind get parameter in your query
Example:-
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM `$table` WHERE `$fieldname`=:id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $id);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
You are not executing the SQL statement in your code. Try executing the below implementation :
$db = new PDO('mysql:host=localhost;dbname=rfid_db;charset=utf8mb4', 'username', 'password');
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //optional
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); //optional
$stmt = $db->prepare('insert into sensor(value) values(:val)');
$stmt->bindParam(':val', $_GET["value"], PDO::PARAM_INT);
$stmt->execute();
Also for detailed study on PDO try referencing the documentation here http://php.net/manual/en/pdo.prepared-statements.php

query error when access clearDB database using php on Heroku

I can access clearDB database well by using Mysql Workbench.
But when I query database by using php on Heroku, it always fail.
This is my code:
$url=parse_url(getenv("CLEARDB_DATABASE_URL"));
$dbhost = $url["host"];
$dbuser = $url["user"];
$dbpass = $url["pass"];
$dbname = substr($url["path"],1);
mysqli_connect($dbhost, $dbuser, $dbpass);
mysqli_select_db($dbname);
$sql = "SELECT * FROM `user_info` WHERE `user_account`='".$user_account."'";
$result = mysqli_query($sql) or die('MySQL query error');
user_account is a table in the database, $user_account is a input variable from client user
help me
thanks
You're not passing the link to mysqli_query(). You need to either do that, or use the object oriented style and call query() on the connection.
You also have a possible SQL injection there, because $user_account could contain "foo' OR 1 OR '", returning all rows (and that's just a simple, not very evil case), so you should escape that using mysqli_real_escape_string(), or even better, use prepared statements.
Finally, instead of or die(), how about extracting error information properly, or even configuring mysqli to throw exceptions?
<?php
$url = parse_url(getenv("CLEARDB_DATABASE_URL"));
$server = $url["host"];
$username = $url["user"];
$password = $url["pass"];
$db = substr($url["path"], 1);
$conn = new mysqli($server, $username, $password, $db);
$sql = "SELECT * FROM `user_info` WHERE `user_account`='".$conn->real_escape_string($user_account)."'";
if($result = $conn->query($sql)) {
foreach($result as $row) {
// ...
}
} else {
throw new Exception($conn->error);
}

Fatal error: Call to a member function query() on a non object

I've got this error:
Fatal error: Call to a member function query() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/login.php on line 8
The line is this:
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
This is login.php:
$user = $_POST['user'];
$pass = $_POST['pass'];
$pw = md5($pass);
include_once('connect.php');
function check_login($user,$pw,&$result){
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
$cont = 0;
while($row = $res->fetch_object()){
$cont++;
$result = $row;
}
if($cont == 1){
return 1;
}
else{
return 0;
}
}
if(!isset($_SESSION['userid'])){
if(isset($_POST['login'])){
if(check_login($user,$pw,$result) == 1){
session_start();
$_SESSION['userid'] = $result->id_user;
header("location:index.php?var=ok");
}
else{
header('location:index.php?var=log');
}
}
}
And the code of connect.php :
$mysqli = new mysqli('localhost', 'root', 'pass', 'cms' );
if ($mysqli->connect_error) {
die('Error de Conexión (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
What could be the problem? Problems connecting the database?
This is most likely a scoping issue. This means that the variable $mysqli that you define in your included file is outside of the check_login function's scope (i.e. is not known inside this function).
You could try to get the $mysqli variable from global scope with
function check_login($user,$pw,&$result){
global $mysqli;
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
// ...
Edit: Oh, and you should also mind the SQL injection vulnerabiliy in your code. Use prepared statements to prevent this issue (or at least escape your input variables with a function like mysqli::real_escape_string).
function check_login($user,$pw,&$result){
global $mysqli;
$res = $mysqli->query("SELECT * FROM user WHERE user='$user' and password='$pw'");
$cont = 0;
while($row = $re[...]
Mind the "global". This puts the var in the scope of your method.
This is a quick and dirty solution, but will work in this case.
It looks like your $mysqli variable is not being set properly within the scope of your code thats executing the query. Can you confirm that $mysqli is indeed a mysqli object and not, say, set to null?
You can check this by doing: echo print_r($mysqli); right before you call the ->query method in your code.
If it is not set properly, track the variable backward in your code until you see why
variable $mysqli in function check_login is out of scope (it is declare outside the function) so it is null.
public function connectDB($DBServer, $DBUser, $DBPass, $DBName) {
global $con;
$con = new mysqli($DBServer, $DBUser, $DBPass, $DBName) or die ("Error occured");
return $con;
and then pass $con in all the functions that you define or run wherever.

Categories