PHP: Getting insert confirmation on prepared statement - php

I am a newbie to prepared statements and trying to get something simple to work.
This is my DB table:
`unblocker_users` (
`uno` bigint(20) NOT NULL AUTO_INCREMENT,
`user_email` varchar(210) DEFAULT NULL,
`pw_hash` varchar(30) DEFAULT NULL,
`email_confirmed` tinyint(4) DEFAULT NULL,
`total_requests` bigint(20) DEFAULT NULL,
`today_date` date DEFAULT NULL,
`accessed_today` tinyint(4) DEFAULT NULL,)
and this is my function to insert some test data
function add_new_user($e_mail1)
{
require_once "db.php";
$stmt = $mysqli->prepare("INSERT INTO unblocker_users VALUES ('',?, ?,0,0,?,0)");
$stmt->bind_param('sss', $e_mail1, $this->genRandomString(1),$this->today_date());
$stmt->execute();
$stmt->close();
// ####### Below line is giving an error ########
$done = $stmt->affected_rows;
return $done;
}
As you can see above, i have marked the line that is giving me an error.
Warning: unblocker_class::add_new_user() [unblocker-class.add-new-user]: Property access is not allowed yet in...
Where did I go wrong?
How can i get some sort of confirmation that a row has been inserted successfully?
Thanks!

you close the prepared statement BEFORE you want to access its affected rows
$done = $stmt->affected_rows;
$stmt->close();
return $done;

Related

Mysql does not store blob column data

I have strange problem that I am unable to figure out, any help would be appreciated!.
The problem is I am trying to store an object into mysql database, when I execute the insertion command I run successfully, but when I check the table, all columns have the new inserted data expect the column with Blob datatype.
here is the table
CREATE TABLE `uc_opportunities` (
`post_id` int(11) NOT NULL AUTO_INCREMENT,
`org_id` int(11) DEFAULT NULL,
`dateTime` int(11) NOT NULL,
`subject` varchar(200) NOT NULL,
`text` varchar(2000) DEFAULT NULL,
`zipcode` varchar(10) NOT NULL,
`location` varchar(100) DEFAULT NULL,
`schedule` blob NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8;
and here is the insertion function:
public function addOpportunity($org_id)
{
global $mysqli,$emailActivation,$websiteUrl,$db_table_prefix; //
echo "inside add opportunity<br>";
var_dump($this->schedule);
$stmt = $mysqli->prepare("INSERT INTO ".$db_table_prefix."opportunities (
org_id,
dateTime,
subject,
text,
zipcode,
schedule
)
VALUES (
?,
?,
?,
?,
?,
?
)");
$schedule_serialized = serialize($this->schedule);
$stmt->bind_param("iissib", $org_id, $this->dateTime, $this->subject,$this->postText, $this->zipcode, $schedule_serialized );
$result = $stmt->execute();
echo "execution result ".$result."<br>";
$inserted_id = $mysqli->insert_id;
$stmt->close();
$this->post_id = $inserted_id;
}
All columns except schedule are inserted, I check if the insertion function receive the schedule correctly using var_dump($this->schedule) and it is correct. What do you think might be the problem?
Thank you
Please check out the mysqli documentation in reference to saving blob data and mysql config for max_allowed_packet. It's possible this could be your issue since I don't know how big your serialized data is:
php.net mysqli
first of all,change your data if it is image,audio,document etc into binary and schedule column to longBlob then run your insert command.Some times due to larger binary data insert doesn`t work.So give a try

Extracting data from a column using mysqli::bind_result()

My query returns with null in my php code , but when I enter the same query into phpmyadmin it returns the row to which it belongs. Here is the database I am using
CREATE TABLE `payment`.`users`(
`u_id` int(12) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`passwd` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY (`email`)
) ENGINE=MyISAM;
and here is the code i am using that is returning null when it clearly works in phpmyadmin.
function getUserId($email, $passwd) {
$mysqli = db_connect();
$query = "SELECT `u_id` FROM `payment`.`users` WHERE `email`='$email' AND `passwd`='$passwd' ORDER BY 1";
if ($stmt = $mysqli->prepare($query)) {
/* execute query */
$stmt->execute();
$stmt->bind_result($u_id);
while ($stmt->fetch()) {
return $u_id;
}
}
}
The thing is that you are using variables in your php code to set the values. In phpMyAdmin you're inserting values directly, therefore the problem may be in the values inserted.
First of all use PDO's bindParam() or mysqli's bind_param() statements as they sanitize inputs and help you avoid SQL Injections.
Second good thing about using prepared statements and binding params is that you can specify the type of the data being binded to to the query which in most cases will fix such problems. Though in your case you're probably inserting strings.

How to Insert in MySQLi in prepared statement

Hi! My table structure looks like this:
CREATE TABLE IF NOT EXISTS `search` (
`key` varchar(255) NOT NULL,
`id` int(15) NOT NULL auto_increment,
UNIQUE KEY `key` (`key`),
KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
And this is how I try to add data into my table:
$stmt = $mysqli->prepare("INSERT INTO search(key) VALUES (?)");
$stmt->bind_param('s',$keyword);
$stmt->execute();
$stmt->close();
This is what I got:
Call to a member function bind_param() on a non-object
But it works when I do this:
$stmt = $mysqli->prepare("INSERT INTO search VALUES (?,NULL)");
$stmt->bind_param('s',$keyword);
$stmt->execute();
$stmt->close();
Is there any other way besides putting NULL to the VALUES?
is there any necessity that i should put NULL to auto increments?
No.
And there is no necessity in finding an answer by means of wild guess either.
You have to get the error message instead.
For which purpose always have this line right before connecting to mysqli:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
speaking for the certain query, key is a mysql keyword and have to be quoted in backticks
INSERT INTO search(`key`) VALUES (?)

mysql_affected_rows Returns False On Successful Query?

I am having a difficult time sorting through this PHP/MySQL issue. Let me show you my database, and explain my situation:
Create table:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(50) NOT NULL AUTO_INCREMENT,
`active` varchar(20) NOT NULL,
`activation` varchar(15) NOT NULL,
`firstName` longtext NOT NULL,
`lastName` longtext NOT NULL,
`passWord` longtext NOT NULL,
`changePassword` text NOT NULL,
`emailAddress1` longtext NOT NULL,
`emailAddress2` longtext NOT NULL,
`emailAddress3` longtext NOT NULL,
`role` longtext NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `name` (`firstName`,`lastName`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;
Insert a value:
INSERT INTO `users` (
`id` ,
`active` ,
`activation` ,
`firstName` ,
`lastName` ,
`passWord` ,
`changePassword` ,
`emailAddress1` ,
`emailAddress2` ,
`emailAddress3` ,
`role`
) VALUES (
NULL, '1000000000', 'abcdefghijklmno', 'John', 'Smith', '*24D7FB97963C40FE5C56A6672F9560FC8B681508', 'on', 'john#gmail.com', '', '', 'User'
);
Update a value:
$affected = mysql_query(UPDATE users SET passWord = PASSWORD('a9eb42e1b3be829ef42972ea9abab334'), changePassword = 'on' WHERE emailAddress1 = 'john#gmail.com', $dbID);
if (mysql_affected_rows($affected)) {
//Never runs
}
The above UPDATE query executes just fine in my script, phpMyAdmin, and the MySQL terminal. However, mysql_affected_rows($affected) always gives me this error:
Warning: mysql_affected_rows() expects parameter 1 to be resource, boolean given
I know that this means my query failed, but every time I go into the database, I see that the values have been updated.
Removing the parameter from the function appears to clear things up. However, I rather have the identifier as the function parameter, just to be sure what I am referring to, and for code insurance.
Any idea why this might be doing this?
Thank you for your time.
http://php.net/mysql_query
Return Values
...
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
And:
int mysql_affected_rows ([ resource $link_identifier = NULL ] )
This means mysql_affected_rows wants a mysql connection resource as an argument. Not the result of mysql_query, and most certainly not if that result is only true or false. You use it like this:
$successful = mysql_query('UPDATE ...');
if ($successful) {
echo 'Affected rows: ' . mysql_affected_rows();
} else {
echo 'Fail: ' . mysql_error();
}
change:
$affected = mysql_query(UPDATE users SET passWord = PASSWORD('a9eb42e1b3be829ef42972ea9abab334'), changePassword = 'on' WHERE emailAddress1 LIKE 'john#gmail.com', $dbID);
and execute
In my case, it was that the new value of updating was equal to the old value, so no change is made and the result of the mysql_affected_rows() would be 0 or false

function fetch() on a non-object in PHP

I have this url,
http://webworks.net/ww.incs/forgotten-password-verification.php?verification_code=974bf747124c69f12ae3b36afcaccc68&email=myemail#gmail.com&redirect=/ww.admin/index.php
And this gives the following error.
Fatal error: Call to a member function fetch() on a non-object in
/var/www/webworks/ww.incs/basics.php on line 23
Call Stack: 0.0005 338372 1. {main}()
/var/www/webworks/ww.incs/forgotten-password-verification.php:
0 0.0020 363796 2. dbRow()
/var/www/webworks/ww.incs/forgotten-password-verification.php:18
The forgotten-password-verification.php
require 'login-libs.php';
login_check_is_email_provided();
// check that a verification code was provided
if(
!isset($_REQUEST['verification_code']) || $_REQUEST['verification_code']==''
){
login_redirect($url,'novalidation');
}
// check that the email/verification code combination matches a row in the user table
// $password=md5($_REQUEST['email'].'|'.$_REQUEST['password']);
$r=dbRow('select * from user_accounts where
email="'.addslashes($_REQUEST['email']).'" and
verification_code="'.$_REQUEST['verification_code'].'" and active'
);
if($r==false){
login_redirect($url,'validationfailed');
}
// success! set the session variable, then redirect
$_SESSION['userdata']=$r;
$groups=json_decode($r['groups']);
$_SESSION['userdata']['groups']=array();
foreach($groups as $g)$_SESSION['userdata']['groups'][$g]=true;
if($r['extras']=='')$r['extras']='[]';
$_SESSION['userdata']['extras']=json_decode($r['extras']);
login_redirect($url);
And login-libs,
require 'basics.php';
$url='/';
$err=0;
function login_redirect($url,$msg='success'){
if($msg)$url.='?login_msg='.$msg;
header('Location: '.$url);
echo 'redirect';
exit;
}
// set up the redirect
if(isset($_REQUEST['redirect'])){
$url=preg_replace('/[\?\&].*/','',$_REQUEST['redirect']);
if($url=='')$url='/';
}
// check that the email address is provided and valid
function login_check_is_email_provided(){
if(
!isset($_REQUEST['email']) || $_REQUEST['email']==''
|| !filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL)
){
login_redirect($GLOBALS['url'],'noemail');
}
}
// check that the captcha is provided
function login_check_is_captcha_provided(){
if(
!isset($_REQUEST["recaptcha_challenge_field"]) || $_REQUEST["recaptcha_challenge_field"]==''
|| !isset($_REQUEST["recaptcha_response_field"]) || $_REQUEST["recaptcha_response_field"]==''
){
login_redirect($GLOBALS['url'],'nocaptcha');
}
}
// check that the captcha is valid
function login_check_is_captcha_valid(){
require 'recaptcha.php';
$resp=recaptcha_check_answer(
RECAPTCHA_PRIVATE,
$_SERVER["REMOTE_ADDR"],
$_REQUEST["recaptcha_challenge_field"],
$_REQUEST["recaptcha_response_field"]
);
if(!$resp->is_valid){
login_redirect($GLOBALS['url'],'invalidcaptcha');
}
}
basics.php is,
session_start();
function __autoload($name) {
require $name . '.php';
}
function dbInit(){
if(isset($GLOBALS['db']))return $GLOBALS['db'];
global $DBVARS;
$db=new PDO('mysql:host='.$DBVARS['hostname'].';dbname='.$DBVARS['db_name'],$DBVARS['username'],$DBVARS['password']);
$db->query('SET NAMES utf8');
$db->num_queries=0;
$GLOBALS['db']=$db;
return $db;
}
function dbQuery($query){
$db=dbInit();
$q=$db->query($query);
$db->num_queries++;
return $q;
}
function dbRow($query) {
$q = dbQuery($query);
return $q->fetch(PDO::FETCH_ASSOC);
}
define('SCRIPTBASE', $_SERVER['DOCUMENT_ROOT'] . '/');
require SCRIPTBASE . '.private/config.php';
if(!defined('CONFIG_FILE'))define('CONFIG_FILE',SCRIPTBASE.'.private/config.php');
set_include_path(SCRIPTBASE.'ww.php_classes'.PATH_SEPARATOR.get_include_path());
I am not sure how to solve the problem.
My db:
CREATE TABLE IF NOT EXISTS `user_accounts` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` text,
`password` char(32) DEFAULT NULL,
`active` tinyint(4) DEFAULT '0',
`groups` text,
`activation_key` varchar(32) DEFAULT NULL,
`extras` text,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=10 ;
INSERT INTO `user_accounts` (`id`, `email`, `password`, `active`, `groups`, `activation_key`, `extras`) VALUES
(2, 'bla#blabla.com', '6d24dde9d56b9eab99a303a713df2891', 1, '["_superadministrators"]', '5d50e39420127d0bab44a56612f2d89b', NULL),
(3, 'user#blabla.com', 'e83052ab33df32b94da18f6ff2353e94', 1, '[]', NULL, NULL),
(9, 'myemail#gmail.com', '9ca3eee3c43384a575eb746eeae0f279', 1, '["_superadministrators"]', '974bf747124c69f12ae3b36afcaccc68', NULL);
The answer is, I believe, in this:
the table user_accounts:
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`email` text,
`password` char(32) DEFAULT NULL,
`active` tinyint(4) DEFAULT '0',
`groups` text,
`activation_key` varchar(32) DEFAULT NULL,
`extras` text,
PRIMARY KEY (`id`)
and
the 'forgotten-password-verification.php':
// check that the email/verification code combination matches a row in the user table
// $password=md5($_REQUEST['email'].'|'.$_REQUEST['password']);
$r=dbRow('select * from user_accounts where
email="'.addslashes($_REQUEST['email']).'" and
verification_code="'.$_REQUEST['verification_code'].'" and active'
);
where verification_code is not a valid part of user_accounts.
Change it and it should work ;)
Line 23 of basics.php is probably:
return $q->fetch(PDO::FETCH_ASSOC);
This means that $q is not the object you expected it to be (seems like a PDOStatement). Apparently, it is returned from the dbQuery function, which returns the result of PDO::query. PDO::query will return a PDOStatement on success, or FALSE on error.
It means that you query is erroneous. Most likely this one:
$r=dbRow('select * from user_accounts where
email="'.addslashes($_REQUEST['email']).'" and
verification_code="'.$_REQUEST['verification_code'].'" and active'
);
The problem is probably the end of your query, which does not look like valid SQL:
and active
Also, since you are using PDO, you should take advantage of prepared statements, since your code is actually open to SQL injection. addslashes is not a proper mechanism for escaping database parameters, and you should not use $_REQUEST unless you know what you are doing. You should use $_GET, $_POST or $_COOKIE directly.
For your securing your queries, use prepared statements, and check the return values:
function dbQuery($query, array $params = array()){
$db=dbInit();
$q=$db->prepare($query); // use prepare() instead of query()
$q->execute($params); // automatically bind the parameters with execute()
$db->num_queries++;
return $q;
}
function dbRow($query, array $params = array()) {
$q = dbQuery($query, $params);
if (!$q) {
// check for errors
throw new Exception('A database error has occured!');
}
return $q->fetch(PDO::FETCH_ASSOC);
}
Then just do:
$r=dbRow('select * from user_accounts where email=? and verification_code=?',
array($_GET['email'], $_GET['verification_code'])
);
There is a problem in password_reminder.php.
In stead of verificatio_code, it was using activation_code.

Categories