How I can check error in my mysqli? [duplicate] - php

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I have a code below... and sometimes this code just give me information that everything is ok, and "success" msg. But new row from insert is not added to database.
I thought: echo $this->mysqli->error; will give me error but it's not working?
if ($stmt = $this->mysqli->prepare("INSERT INTO tournaments ("
. "id_system, "
. "id_rank_admin, "
. "id_tournament_class, "
. "id_season, "
. "tournament_name,"
. "description,"
. "city,"
. "address,"
. "tournament_date,"
. "start_time,"
. "entry_fee,"
. "tournament_type,"
. "accepted_expansions,"
. "prices,"
. "additional_info,"
. "status,"
. "organizer_name,"
. "organizer_logo,"
. "organizer_link) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) "))
{
$stmt->bind_param("sssssssssssssssssss",
$this->id_system,
$this->id_rank_admin,
$this->it_tournament_class,
$this->id_season,
$this->tournament_name,
$this->description,
$this->city,
$this->address,
$this->tournament_date,
$this->start_time,
$this->entry_fee,
$this->tournament_type,
$this->accepted_expansions,
$this->prices,
$this->additional_info,
$this->status,
$this->organizer_name,
$this->organizer_logo,
$this->organizer_link);
$stmt->execute();
$stmt->close();
}
else
{
echo $this->mysqli->error;
}

$ok=$stmt->execute();
if($ok)
{
echo "Query Executed Successfully";
}
else
{
echo(mysqli_error($link));
}
The mysqli->execute what it does is returns true or false based on it you can get your error i'm not in to too much of mysqli oop way so if any syntax is wrong correct it

I found this here: http://php.net/manual/en/mysqli.error.php
string mysqli_error ( mysqli $link )
Returns the last error message for the most recent MySQLi function call that can succeed or fail.
Might give you a better understanding of where the error is.

Try this:
$link = mysqli_connect("localhost", "my_user", "my_password", "db");
else
{
echo(mysqli_error($link));
}

Related

Problem with PHP INSERT in to MySQL database

I am hoping that I've just been looking at and debugging this code too long (days now!) and I'm just not seeing the problem.
I'm obviously trying to add an entry in to a MySQL database via my PHP code. To use the classic phrase "this code has always worked before and now it doesn't and I didn't change anything" ;-)
My code, with my current debugging traps, looks like this:
// Prepare SQL Insert
$strInsert = "INSERT INTO Horses ( HorseName, HorseYOB, HorseCOB, HorseSex, HorseYOD, HorseDead, FAM, FDM) " .
"VALUES (:HORSENAME, :HORSEYOB ,:HORSECOB, :HORSESEX, :HORSEYOD, :HORSEDEAD, :FAM, :FDM)";
$DBInsertHorse = $DB->prepare($strInsert);
// Insert new Horse
$iCtr = 0;
do {
try {
$DBInsertHorse->execute(array(
'HORSENAME' => strtoupper($HorseName),
'HORSEYOB' => $YOB,
'HORSECOB' => $COB,
'HORSESEX' => strtoupper($HorseSex),
'HORSEYOD' => $YOD,
'HORSEDEAD' => $bDead,
'FAM' => $FAM,
'FDM' => $FDM)
);
}
catch (Exception $error) {
die($error->getMessage());
}
} while ($find($DB, strtoupper($HorseName), $YOB, $COB) == false && ++$iCtr < MAX_INSERT_ATTEMPTS);
// Could not insert
if ($iCtr == MAX_INSERT_ATTEMPTS) {
// DEBUG HORSE IMPORT
if (is_null($HorseName))
$HorseName = 'NULL';
if (is_null($YOB))
$YOB = -2;
if (is_null($COB))
$COB = 'NULL';
if (is_null($HorseSex))
$HorseSex = 'NULL';
if (is_null($YOD))
$YOD = -2;
if (is_null($bDead) || !$bDead)
$Dead = -2;
if (is_null($FAM))
$FAM = 'NULL';
if (is_null($FDM))
$FDM = 'NULL';
error_log('INSERT ERROR: Horse: \'' . strtoupper($HorseName) . '\' - YOB: ' . $YOB . ' - COB: \'' . $COB . '\' - SEX: \'' . strtoupper($HorseSex) . '\' - YOD: ' . $YOD . ' - Dead: ' . $bDead . ' - FAM: ' . $FAM . ' - FDM: ' . $FDM);
return(false);
}
If I go my favourite SQL editor (SQLPro for MySQL) and I enter in the insert manually it works fine:
INSERT INTO Horses (HorseName, HorseYOB, HorseCOB, HorseSex, HorseYOD, HorseDead, FAM, FDM)
VALUES ('HorseName', 2001, null, 'M', null, false, null, null)
For info:
The find() function used is my own and wraps a "SELECT FROM ..." query and works fine. If I do a SELECT from the Horses table in the database afterwards the Horse was never added.
MAX_INSERT_ATTEMPTS is my constant and the value is currently set at 5.
I'm working with MaMP PRO and I've looked in my PHP error log, where only the message I sent there appears and no other errors and in my MySQL error log, where no error message appears.
I can't figure out where to look next and I'm hoping whatever my stupid error might be is going to jump out at someone else looking at my code.
Thanks for looking and for any ideas, suggestions or corrections you may have.
UPDATED CODE WITH DEBUGGING
do {
try {
$DBInsertHorse->bindValue(':HORSENAME', strtoupper($this->Name));
$DBInsertHorse->bindValue(':HORSEYOB', $this->YOB);
$DBInsertHorse->bindValue(':HORSECOB', $this->COB);
$DBInsertHorse->bindValue(':HORSESEX', strtoupper($this->Sex));
$DBInsertHorse->bindValue(':HORSEYOD', $this->YOD);
$DBInsertHorse->bindValue(':HORSEDEAD', (int)$this->Dead);
$DBInsertHorse->bindValue(':FAM', $this->FAM);
$DBInsertHorse->bindValue(':FDM', $this->FDM);
$DBInsertHorse->execute();
}
catch (PDOException $e) {
error_log('SQL INSERT ERROR: ' . $e->getMessage());
}
} while($this->find($DB, strtoupper($this->Name), $this->YOB, $this->COB) == false && ++$iCtr < MAX_INSERT_ATTEMPTS);
As #BillKarwin mentioned I was missing a proper call to
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Once that was in place I was able to see where the error was. This error apparently has appeared since my upgrade to PHP 7.2.10.
I also changed my call to array to a list of calls to bindValue... I may go back to array() but that's not important. ;-)
The PHP code did not like my passing "false" to a tinyint field. I had to type the variable with a call to (int)varname and everything works fine now.
(int)$this->Dead;
THANK YOU ALL!
Check this, it's tested and it works. Also check do while statement.
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO Horses ( HorseName, HorseYOB, HorseCOB, HorseSex, HorseYOD, HorseDead, FAM, FDM)
VALUES (:HORSENAME, :HORSEYOB ,:HORSECOB, :HORSESEX, :HORSEYOD, :HORSEDEAD, :FAM, :FDM)");
$stmt->bindParam(':HORSENAME',$HorseName);
$stmt->bindParam(':HORSEYOB', $YOB);
$stmt->bindParam(':HORSECOB', $COB);
$stmt->bindParam(':HORSESEX', $HorseSex);
$stmt->bindParam(':HORSEYOD', $YOD);
$stmt->bindParam(':HORSEDEAD', $bDead);
$stmt->bindParam(':FAM', $FAM);
$stmt->bindParam(':FDM', $FDM);
// insert a row
$HorseName = strtoupper($HorseName);
$YOB = "John";
$COB = "John";
$HorseSex = strtoupper($HorseSex);
$YOD = "John";
$bDead = "John";
$FAM = "John";
$FDM = "John";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;

Don't show any data data [duplicate]

This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 4 years ago.
Here is my php and mysql code. It don't show any data . please tell me where is my error:
<?php
$ddaa = mysql_query("SELECT ref FROM users WHERE id='$uid'");
$mallu2 = mysql_query("SELECT mallu FROM users WHERE id='$ddaa'");
$result = mysql_fetch_array($mallu2);
echo $result['mallu'];
?>
You can use Mysqli,mysql is deprecated
a little example:
conection to db test
$mysqli = new mysqli('127.0.0.1', 'user', 'password', 'test');
if ($mysqli->connect_errno) {
echo "Error: Errot on connection : \n";
echo "Errno: " . $mysqli->connect_errno . "\n";
}
// the query
$sql = "SELECT ref FROM users WHERE id=$uid";
//if don't have result
if ($resultado->num_rows === 0) {
echo "we can't find data with $uid. try again !.";
exit;
}
//print the result
while ($dato = $resultado->fetch_assoc()) {
echo $dato['ref'];
}
Mysqli Php documentation

Error produced from mysql select

I'm currently learning MySql, but ive hit this problem.
the following code should just query the db for everything in the users table. but it returns this error. Error: SELECT * FROM users which helps me not at all. I am able to successfully insert an item into the database, but I am unable to select from it. I've also tried $sql = "SELECT * FROM ama.users"; my DB structure is
ama
|-users
any help would be much appreciated.
$conn = new mysqli($_ENV['OPENSHIFT_MYSQL_DB_HOST'],$_ENV['OPENSHIFT_MYSQL_DB_USERNAME'], $_ENV['OPENSHIFT_MYSQL_DB_PASSWORD'], 'ama');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$username = "Doe";
$password = "johnexample";
$sql = "SELECT * FROM users";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
From the PHP Manual:
mysqli::query will return object in success and return false in failure.
So you can use it without checking data type (===):
if ($conn->query($sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
For more better understanding you can use var_dump() and check what are you getting like:
var_dump($conn->query($sql));
Documentation says:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
So, do something like
$result= $db->query($sql);
and then check the rows in $result

Protect from injections and right syntax for $_GET method

So, I am trying to use the get method while protecting from injections. I'm trying to get data from the database and echo it out to a page. I think it's pretty obvious what I'm trying to do with the code below but i need help with using the right syntax.
Can someone show me the right syntax for the prepare statement to get data from a database using mysqli that is protected from injections?
I've looked on this site can't seem to find what I'm looking for and the PHP site I couldn't find an up to date method. Thanks for all the help.
<?php
$mysqli = new mysqli("", "", "", "");
if ($mysqli->connect_error) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_error . ") " . $mysqli->connect_error;
}
$stmt = $mysqli->stmt_init();
if($stmt->prepare("SELECT 'name,name' FROM 'table' WHERE 'name, name' = ?,?")) {
}
if (!$stmt->bind_param('si', $_GET['name'], $_GET['name'])); {
echo "Binding parameters failed: (" . $stmt->error . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->error . ") " . $stmt->error;
}
if (!$stmt->fetch()); {
echo "Binding parameters failed: (" . $stmt->error . ") " . $stmt->error;
}
$stmt->close();
?>
your sql is wrong:
if($stmt->prepare("SELECT 'name,name' FROM 'table' WHERE 'name, name' = ?,?")) {
must be
if($stmt->prepare("SELECT name, name FROM table WHERE name=? AND name=? ")) {
Double the expressive name, I used only because of the question.
The following is clearer:
if($stmt->prepare("SELECT astring, ainteger FROM table WHERE astring=? AND ainteger=? "))
{
if (!$stmt->bind_param('si', $_GET['astring'], $_GET['ainteger'])) {
Take out some time to write the question carefully. If two variables are used, then designate different, everything else just confused.
Update :
Before you use bind_param()
You have to test all $_GET["xx"].
if (isset($_GET['name']))
When you call a function, terminated with ; for example:
if (!$stmt->bind_param('si', $_GET['name'], $_GET['name'])); {
Then the curly braces are useless, no matter the if gets true or false!
The following code after if (!$stmt->bind_param(...)); will always be executed, because the command, is finished.
if (!$stmt->bind_param('si', $_GET['name'], $_GET['name'])); {
echo "Binding parameters failed: (" . $stmt->error . ") " . $stmt->error;
}
It took a long time until I found this error. It is easily overlooked.
That's why you always get your own error messages.
to protect from sql injection, you should first make a connection to your mysql database and after that you should surround your $_GET with mysql_real_escape_string(), like this:
mysql_real_escape_string($_GET['name'])
or to use the newer function
mysqli_real_escape_string($_GET['name'])
This is better solution if you whant to protect all GET inputs:
function GET($name=NULL, $value=false)
{
$content=(!empty($_GET[$name]) ? trim($_GET[$name]) : (!empty($value) && !is_array($value) ? trim($value) : false));
if(is_numeric($content))
return preg_replace("#([^0-9])#Ui", "", $content);
else if(is_bool($content))
return ($content?true:false);
else if(is_float($content))
return preg_replace("#([^0-9\,\.\+\-])#Ui", "", $content);
else if(is_string($content))
{
if(filter_var ($content, FILTER_VALIDATE_URL))
return $content;
else if(filter_var ($content, FILTER_VALIDATE_EMAIL))
return $content;
else if(filter_var ($content, FILTER_VALIDATE_IP))
return $content;
else if(filter_var ($content, FILTER_VALIDATE_FLOAT))
return $content;
else
return preg_replace("#([^a-zA-Z0-9\+\-\_\*\#\$\!\;\.\?\#\:\=\%\/\ ]+)#Ui", "", $content);
}
else false;
}
Just instead $_GET['something'] you use GET('something') and you have option to put default value if GET value don't exists. And lather in MySQL query you can use escape string or prepared state to full protect your query.

Cannot pass parameter when attempting prepared statement

I'm attempting to learn prepared statements right now in PHP/MYSQL because of many suggestions around here. I keep getting this error:
Fatal error: Cannot pass parameter 2 by reference in C:\xampp\htdocs\blog\admin\create.php on line 57
Can anyone tell me how to fix this problem? I've been searching around and I can't find anything that will help me solve this.
Here is my code:
<?php
require_once '../config.php';
// Check to see if the title was entered from new.php
if ($_POST['title'])
{
$title = $_POST['title'];
} else {
echo "No title was entered. Please go back. <br />";
}
// Check to see if the body was entered from new.php
if ($_POST['body'])
{
$body = $_POST['body'];
} else {
echo "No body was entered. Please go back. <br />";
}
// Get the date
$date = time();
// ID = NULL because of auto-increment
$id = 'NULL';
// If magic_quotes_gpc returns true then it's enabled on the serever and all variables will be
// automatically escaped with slashes. If it isn't true then it's done manually
if (!get_magic_quotes_gpc())
{
$title = addslashes($title);
$body = addslashes($body);
$date = addslashes($date);
}
// Connect to the database
$db = new mysqli('localhost','username','password','database');
// Check to see if the connection works
if ($db->connect_errno)
{
echo 'Error: Could not connect to database. Please try again.';
exit;
}
// Prepared statement for a query to place something in the database
if(!($stmt = $db->prepare("insert into pages (id, title, body, date) values (?,?,?,?)")))
{
echo "Prepare failed: (" .$db->errno . ")" . $db->error;
}
// THIS IS THE LINE WHERE I'M RECEIVING THE ERROR!!!!!!!!
if (!$stmt->bind_param('isss', ''.$id.'', ''.$title.'',''.$body.'',''.$date.''))
{
echo "Binding parameters failed: (" .$stmt->errno. ")" . $stmt->error;
}
if (!$stmt->execute())
{
echo "Execute failed: (" .$stmt->errno . ") " .$stmt->error;
}
$db->close;
?>
You should have a look at the corresponding mysqli_stmt::bind_param documentation. More precisely, have a look at the function's definition:
bool mysqli_stmt::bind_param ( string $types , mixed &$var1 [, mixed &$... ] )
Notice the mixed &$var1 part? This basically states that your paramters are passed by reference and not by value (which would look like mixed $var1 - the & makes the difference).
Now, the problem with your invocation is that you are trying to pass an expression rather than a variable by reference. From the PHP documentation:
The following things can be passed by reference:
- Variables, i.e. foo($a)
- New statements, i.e. foo(new foobar())
- References returned from functions, [...]
The simple remedy is to first call the binding with uninitialized variables which are then assigned your processed input data, i.e.
// Prepared statement for a query to place something in the database
$stmt = $db->prepare("insert into pages (id, title, body, date) values (?,?,?,?)");
if ( !$stmt ) {
echo "Prepare failed: (" .$db->errno . ")" . $db->error;
}
if ( !$stmt->bind_param('isss', $stmt_id, $stmt_title, $stmt_body, $stmt_date) ) {
echo "Binding parameters failed: (" .$stmt->errno. ")" . $stmt->error;
}
$stmt_id = (int) $id;
$stmt_title = (string) $title;
$stmt_body = (string) $body;
$stmt_date = (string) $date;
if ( !$stmt->execute() ) {
echo "Execute failed: (" .$stmt->errno . ") " .$stmt->error;
}

Categories