Php use of bindParam in SQLite - php

When I try to add something to the sqlite databse the result is always false. Where is the error? I don't get an exception so I think the code is correct by syntax. Please help me
public function add(ChatMessage $chatMessage){
$stmt = $this->db->prepare('INSERT INTO chatmessage(id,authorName,message) VALUES(:id,:authorName,:message)');
$stmt->bindParam(':id',$id);
$stmt->bindParam(':authorName',$authorName);
$stmt->bindParam(':message',$message);
$id = $chatMessage->getID();
$authorName = $chatMessage->getAuthorName();
$message = $chatMessage->getMessage();
$result = $stmt->execute();
if($result == false) return false;
$chatMessage->setID($this->db->lastInsertId());
$chatMessage->setAuthorName($this->db->lastInsertId());
$chatMessage->setMessage($this->db->lastInsertId());
$this->chatMessages[]=$chatMessage;
}

Related

MySQL Prepared statement confusion

Ok, so I am having a lot of trouble with Prepared statements. I've done hours of research and still can't seem to fully understand everything...
I really feel like I need to understand Prepared statements because I was just about to release a few new free APIs on my website (which require API Key to execute API) but I recently realized how insecure everything is.... I can simply use SQL injection to bypass API Key check, e.g. 'OR'1'='1
Here is how I validate API Key:
$apikey = $_GET['key'];
$sql = "SELECT * FROM `table` WHERE `key` = '$apikey'";
$query = mysqli_query($con, $sql);
if($query)
{
$fetchrow = mysqli_fetch_row($query);
if(isset($fetchrow[0]))
{
echo "API Key is valid!";
}
else
{
echo "API KEY is invalid";
}
}
And like mentioned above this can easily be bypassed by executing my API like this
http://website.com/api.php?key='OR'1'='1
This really scared me at first, but then I did some research and learned a good way to prevent any form of SQL injection is to use prepared statement, so I did a lot of research and it just seems quite complicated to me :/
So I guess my question is, how can I take my above code, and make it function the same way using prepared statements?
Probably everything you need:
class Database {
private static $mysqli;
Connect to the DB:
public static function connect(){
if (isset(self::$mysqli)){
return self::$mysqli;
}
self::$mysqli = new mysqli("DB_HOST", "DB_USER", "DB_PASS", "DB_NAME");
if (mysqli_connect_errno()) {
/*Log error here, return 500 code (db connection error) or something... Details in $mysqli->error*/
}
self::$mysqli->query("SET NAMES utf8");
return self::$mysqli;
}
Execute statement and get results:
public static function execute($stmt){
$stmt->execute();
if ($mysqli->error) {
/*Log it or throw 500 code (sql error)*/
}
return self::getResults($stmt);
}
Bind results to the pure array:
private static function getResults($stmt){
$stmt->store_result();
$meta = $stmt->result_metadata();
if (is_object($meta)){
$variables = array();
$data = array();
while($field = $meta->fetch_field()) {
$variables[] = &$data[$field->name];
}
call_user_func_array(array($stmt, "bind_result"), $variables);
$i = 0;
while($stmt->fetch()) {
$array[$i] = array();
foreach($data as $k=>$v)
$array[$i][$k] = $v;
$i++;
}
$stmt->close();
return $array;
} else {
return $meta;
}
}
Class end :)
}
Example of usage:
public function getSomething($something, $somethingOther){
$mysqli = Database::connect();
$stmt = $mysqli->prepare("SELECT * FROM table WHERE something = ? AND somethingOther = ?");
$stmt->bind_param("si", $something, $somethingOther); // s means string, i means number
$resultsArray = Database::execute($stmt);
$someData = $resultsArray[0]["someColumn"];
}
Resolving your problem:
public function isKeyValid($key){
$mysqli = Database::connect();
$stmt = $mysqli->prepare("SELECT * FROM table WHERE key = ? LIMIT 1");
$stmt->bind_param("s", $key);
$results = Database::execute($stmt);
return count($results > 0);
}
PHP automatically closes DB connection so no worries about it.
$sql = "SELECT * FROM `table` WHERE `key` = ?";
if(stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("i", $apikey);
$stmt->execute();
$stmt->bind_result($res);
$stmt->fetch();
$stmt->close();
}
See more - http://php.net/manual/en/mysqli.prepare.php

PHP fetch() not returning results for SELECT query in MySQL

I have a function to search for records by course name:
<?php
function searchByCourse()
{
if (isset($_POST["course_title"])) {
//Copy to local var
$course_title = $_POST["course_title"];
$stmt = self::$conn->prepare("SELECT student_id, student_name, course_title FROM student_info WHERE course_title = ?");
$stmt->bind_param("s", $course_title);
$result = $stmt->execute();
if ($result === FALSE) {
$stmt->close();
return FALSE;
} else {
$results_array = array();
$stmt->bind_result($student_id, $student_name, $course_title_found);
while ($stmt->fetch()) {
echo "Fetch! \n";
$row = array();
$row["student_id"] = $student_id;
$row["student_name"] = $student_name;
$row["course_title"] = $course_title;
$results_array[] = $row;
}
$stmt->close();
return $results_array;
}
} else {
return FALSE;
}
}
?>
The code seems to execute fine but when I test it using curl for course_title=Computing it should return 3 results. However the echo "Fetch!" is never displayed. It seems to be that there is nothing for it to fetch. It's driving me a little crazy. I've checked all the var names in the database and they match up fine. Any ideas what I could be doing wrong here?
EDIT:
This method is part of my class DbHandler. $conn is a protected static MySqli connection object created in function__contruct().
called like this:
$db = new DbHandler();
$db->searchByCourse();
I have other database functions that work fine for this design pattern. The function is being called correctly. I have also checked the $_POST["course_title"] and that is being passed correctly.

PHP sqlsrv_query select statement not working

I want to make a consult to the MSSQLSERVER with a SELECT STATEMENT but the sqlsrv_query is returning FALSE to me.
I already tested the query and its working fine, am I passing the parameters correctly?
Here is my code:
if($conn === false)
{
die(print_r(sqlsrv_errors()));
}
try
{
$email = "somedbemail#email.com";
$sql = "select Usuario.Email, Usuario.Senha FROM Usuario WHERE Usuario.Email = (?)";
$params = array($email);
$stmt = sqlsrv_query( $conn, $sql, $params);
if($stmt != False)
{
if($row = sqlsrv_fetch_Array($stmt))
{
$email_Con = $row['Email'];
$psw_Con = $row['Senha'];
}
else
{
echo "alguma coisa";
}
}
else
{
echo "It always enters here!";
}
Two possible problems.
The first is the format of your query. You are using:
select Usuario.Email, Usuario.Senha FROM Usuario WHERE Usuario.Email = (?)
Where I think you should be doing:
select Usuario.Email, Usuario.Senha FROM Usuario WHERE Usuario.Email = ?
The second is that the An invalid parameter was passed to sqlsrv_query() message is common when the connection is not correct (Reference). So double check that your connection is a valid resource.

user_exists function using mysqli

I';m working on changing my code from using MySQL to MySQLi, and its all seemed to be going fine, but I hit a bit of a wall, I'm currently stuck on changing over my function user_exists and I have tried looking into different reason why and what's going wrong but it seems to be the query, i did var_dump($result) and got the response NULL and was told that its down to my query then, so i tried an sql search on phpmyadmin and got a result so im thinking its down to me binding $username to the ? as the errors i get is of that it cannot find the username im trying to log in with.
function user_exists($username) {
$db = $GLOBALS['db'];
$username = trim($username);
//sql
$sql = "SELECT COUNT(`user_id`) FROM `users` WHERE `username` = ?";
//Prepare
$result = $db->prepare($sql);
//Bind
$result->bind_param('s', $username);
//execute
$result->execute();
//Bind-Results - the 2 codes below are noted out cause im not sure they are needed but have tried with and without them
//$result->bind_result($user_id);
//$result->fetch();
if (false === $result) {
return false;
}
return ($result->num_rows === 1);
}
i can provide the code to my signin.php but im not sure it would be useful as it all worked before i started changing the function.
if someone could point out what, where and why its not working, can you please explain so i can understand so Im good for the future and maybe able to help others out.
You need to call $result->store_result() before checking the number of rows. mysqli_stmt::store_result() will load the result set from the prepared statement so you can access results and properties.
EDIT: This is sort of how I would do it though (untested):
function user_exists($username) {
global $db;
//sql
$sql = "SELECT `user_id` FROM `users` WHERE `username` = ?";
//Prepare
if (!($result = $db->prepare($sql)) return false;
//Bind
if (!$result->bind_param('s', trim($username))) return false;
//execute
if (!$result->execute()) return false;
//Bind-Results
$result->bind_result($user_id);
$result->fetch();
$result->close();
return $user_id ?: false;
}
Here is how my user_exist() function ended up
function user_exists($username) {
$db = $GLOBALS['db'];
//sql
$sql = "SELECT user_id FROM `users` WHERE `username` = ?";
//Prepare
$result = $db->prepare($sql);
//Bind
$result->bind_param('s', $username);
//execute
$result->execute();
//store result
$result->store_result();
if (false === $result) {
return false;
}
return ($result->num_rows === 1);
}
I hope this will help someone. But if any of the code shouldn't be there, i apologise in advance, the code was there for a reason at one point but as im learning all this still, no one advised me that it shouldnt be there.. hope it helps

Mysqli not showing errors properly

I am trying to learn mysqli properly I get most of the functions. One thing left to do is to have proper error reporting across all my layers. I don't understand why the following snippet of code detects an error but won't get the error number nor the error code.
function get_PID_TID_by_PK($con,$ourId)
{
$returned['errno'] ="";
$returned['error'] ="";
//mistake is over here!!!
if(!$stmt = $con->prepare("ELECT gene_name,jgi_protein_id,jgi_transcript_id FROM jgi_transid_protid_match where our_protein_id = ?"))
{
$returned['errno'] = $con->errno;
$returned['error'] = $con->error;
return $returned;
}
if(!$stmt->bind_param('s',$ourId))
{
$returned['errno'] = $stmt->errno;
$returned['error'] = $stmt->error;
return $returned;
}
if(!$stmt->execute())
{
$returned['errno'] = $stmt->errno;
$returned['error'] = $stmt->error;
return $returned;
}
$stmt->bind_result($gene_name,$jgi_protein_id,$jgi_transcript_id);
$stmt->fetch();
$fetchedArray['gene_name'] = $gene_name;
$fetchedArray['jgi_protein_id'] = $jgi_protein_id;
$fetchedArray['jgi_transcript_id'] = $jgi_transcript_id;
//Have to use this hack since query returns an object and not an array and I don't want to make everything object oriented if you don't know what I am talking about just ignore this comment
$returned['assoc'] = $fetchedArray;
return $returned;
}
The mistake is obvious and on the 6th line I wrote ELECT instead of SELECT the program is getting inside that block but the errno and error are null. What am I doing wrong.This code works perfectly fine if I don't break it on purpose.
Are you sure the IF statement is correct?
if(!$stmt = $con->prepare("ELECT gene_name,jgi_protein_id,jgi_transcript_id FROM jgi_transid_protid_match where our_protein_id = ?"))
{
$returned['errno'] = $con->errno;
$returned['error'] = $con->error;
return $returned;
}
Should be
if(($stmt = $con->prepare("ELECT gene_name,jgi_protein_id,jgi_transcript_id FROM jgi_transid_protid_match where our_protein_id = ?")) === FALSE)
{
$returned['errno'] = $con->errno;
$returned['error'] = $con->error;
return $returned;
}
Or split the assignment
$stmt = $con->prepare("ELECT gene_name,jgi_protein_id,jgi_transcript_id FROM jgi_transid_protid_match where our_protein_id = ?");
if($stmt === FALSE)
{
$returned['errno'] = $con->errno;
$returned['error'] = $con->error;
return $returned;
}
I am trying to learn mysqli properly
That's the only mistake you made.
With PDO your code would be... three lines long. And it will report all the errors properly
function get_PID_TID_by_PK($con,$ourId)
{
$stmt = $con->prepare("ELECT gene_name,jgi_protein_id,jgi_transcript_id FROM jgi_transid_protid_match where our_protein_id = ?");
$stmt->execute(array($ourId));
return $stmt->fetch();
}
In the end I decided to go with using http://www.php.net/manual/en/function.set-error-handler.php . I will redesign my code a bit and let the php error handler take care of all the errors and I will make a custom one for my database errors that are happening.

Categories