I Know there are multiple tutorials and stackoverflow answer for the said Question. But none helped.
From my controller I am passing my data as an array.
Now the Stored Procedure created looks like this
BEGIN
DECLARE recCnt Int DEFAULT 0;
#DECLARE rm_id_val Bigint(19);
select count(*) into recCnt from users where user_name = user_name_in;
IF recCnt > 0 THEN
SET rm_id_val = 0;
ELSE
#SET rm_id = rm_id_gen();
INSERT INTO users(user_category, user_name, facebook_id,
password, email, mobile_no, city_name, country_name, view_count, user_type, signup_date, updated_on)
values (user_cat_in,user_name_in, facebook_id_in,
password_in, email_in, mobile_no_in, city_name_in, country_name_in, 0, user_type_in, CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP());
select rm_id into rm_id_val from users where user_name=user_name_in;
INSERT INTO activation (rm_id, no_of_attempt, activation_key, activation_status)
VALUES (rm_id_val,0, activation_key_in, 0);
END IF;
END
Here rm_id_val is OUT param and rest are IN
I passed the $data array to model and the model looks like this
$sql = "CALL signup";
$query = $this->db->query($sql, $data);
return $query->result();
Needless to Say It did not work. Then I tried using a solution from stackoverflow
$this->db->trans_start();
$p1 = $data['user_cat_in'];
$p2 = $data['user_name_in'];
$p3 = $data['facebook_id_in'];
$p4 = $data['password_in'];
$p5 = $data['email_in'];
$p6 = $data['mobile_no_in'];
$p7 = $data['city_name_in'];
$p8 = $data['country_name_in'];
$p9 = $data['view_count'];
$p10 = $data['user_type_in'];
$p11 = $data['signup_date'];
$p12 = $data['updated_on'];
$success = $this->db->query("CALL signup('$p1','$p2','$p3','$p4','$p5','$p6','$p7','$p8','$p9','$p10',#rm_id_val);");
print_r("CALL signup('$p1','$p2','$p3','$p4','$p5','$p6','$p7','$p8','$p9','$p10',#rm_id_val);"); exit();
$out_param_query = $this->db->query('select #rm_id_val as out_param;');
$this->db->trans_complete();
return $success;
Well No output again.
Then I tried MySql Console and executed the following
CALL signup('musician','acacascsacsca','0','cascsacsac','ascascascacacac','acacac','acascacsacs','India','0','1',#rm_id_val);
select #rm_id_val as rmid;
This resulted in
#1414 - OUT or INOUT argument 1 for routine ragamixdb.signup is not a variable or NEW pseudo-variable in BEFORE trigger
Please help me to get this proc called via codeigniter
Thanks and appreciated
Had you tried to set mysql variables.
try to assign/convert php variable to mysql variable using this syntax.
SET #running_sum = 0;
use set of syntaxs in CI like this ,
$this->db->query("SET #your_mysql_variable = ".$your_php_variable);
$this->db->query("SET #your_another_mysql_variable = ".$your_another php_variable);
$this->db->query("CALL your_procedure()");
Related
I want to check if user already liked the post, if so than delete the user from database likes.
I've tried to do an if statement but it wont get to the else and only add likes even when user_id and post_id are the same.
Like.class.php
private function Addlike(){
$conn = db::getInstance();
$query = "insert into likes (post_id, user_id) values
(:post_id, :user_id)";
$statement = $conn->prepare($query);
$statement->bindValue(':post_id',$this->getPostId());
$statement->bindValue(':user_id',$this->getUserId());
$statement->execute();
}
private function Deletelike(){
$conn = db::getInstance();
$query = "DELETE FROM likes WHERE post_id = :post_id
AND user_id =:user_id";
$statement = $conn->prepare($query);
$statement->bindValue(':post_id',$this->getPostId());
$statement->bindValue(':user_id',$this->getUserId());
$statement->execute();
}
public function CheckLike(){
$conn = db::getInstance();
$query = "SELECT COUNT(*) FROM likes WHERE
post_id=:post_id AND user_id=:user_id";
$statement = $conn->prepare($query);
$statement->bindValue(':post_id',$this->getPostId());
$statement->bindValue(':user_id',$this->getUserId());
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
if($result["COUNT(*)"] == 0){
$this->Addlike();
}else{
$this->Deletelike();
}
return $result;
}
If you press like for the first time you should like the post and it should be stored in the database, if you press again you unlike the post and it gets deleted from the database. But now it only does the Addlike function...
I think PDO::FETCH_ASSOC returns a multidimensional array when used with PDOStatement::fetchAll, according to https://www.php.net/manual/en/pdostatement.fetchall.php#refsect1-pdostatement.fetchall-examples.
Try changing your code to something like this and see if it works. You could also try dumping the $result variable to see what the structure looks like.
if($result[0]["COUNT(*)"] == 0){
$this->Addlike();
}else{
$this->Deletelike();
}
If an array index doesn't exist, PHP considers it false, which would explain why you're always adding likes, since false == 0 in PHP.
If you want to avoid this equivalency of false and 0, use the identical operator to also compare types:
if ($result["COUNT(*)"] === 0) {
...
I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax
You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported
You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.
Slowly working through change MSSQL database to MySQL and the final problem is as follows :-
CREATE DEFINER=`root`#`localhost` PROCEDURE `user_GetUserInRole`(
IN $EMail nvarchar(256),
IN $RoleName nvarchar(256),
INOUT $ReturnStatus bit)
BEGIN
DECLARE $UserId char(38);
DECLARE $RoleId char(38);
DECLARE $this_count INT;
SET $UserId = (SELECT UserId FROM server.`user_Data` WHERE EMail = $EMail);
SET $RoleId = (SELECT RoleId FROM server.`user_Roles` WHERE RoleName = $RoleName);
SET $this_count = (SELECT COUNT(*) FROM user_UsersInRoles WHERE UserId = $UserId AND RoleId = $RoleId);
IF ($this_count > 0) THEN
SET $ReturnStatus = 1;
ELSE
SET $ReturnStatus = 0;
END IF;
END
Always returns 0, even when I know the count is equal to 1. I believe that there is an issue with the input variables not being recognized properly by the Where clause in both Select UserId and Select RoleId statements, but I can't see what I'm doing differently to the various helps I've found.
Any help, as always, is greatly appreciated.
EDIT
I have since tried running a simple insert command
CREATE DEFINER=`root`#`localhost` PROCEDURE `test`()
BEGIN
INSERT INTO server.`test_table`
VALUES('test', 'test2');
END
And this hasn't worked either. This leads me to believe that it's actually more of a problem with the PDO call.
$command = "EXEC test";
$stpro = $conn->prepare($command);
$returnvalue = $stpro->execute();
I know that $conn works as straight sql calls in my php definitely work.
EDIT 2
So, turns out EXEC should have been CALL. This now works with the test. As soon as I put any parameters into it though it stops working. Any thoughts?
No need of $Email. Make your parameter declaration like
IN email nvarchar(256)
Change your select inside procedure as below
FROM
SET $UserId = (SELECT UserId FROM server.`user_Data` WHERE EMail = $EMail);
TO
SET #UserId := (SELECT UserId FROM server.`user_Data` WHERE EMail = email);
with that, your procedure should look like
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `user_GetUserInRole`(
IN email nvarchar(256),
IN rolename nvarchar(256),
INOUT retstatus bit)
BEGIN
SET #UserId := (SELECT UserId FROM server.`user_Data` WHERE EMail = email);
SET #RoleId := (SELECT RoleId FROM server.`user_Roles`
WHERE RoleName = rolename);
SET #this_count := (SELECT COUNT(*) FROM user_UsersInRoles
WHERE UserId = #UserId AND RoleId = #RoleId);
IF (#this_count > 0) THEN
SET retstatus = 1;
ELSE
SET retstatus = 0;
END IF;
END$$
DELIMITER ;
Okay, so at this this where I am at the moment #meda. Thought I'd post as a separate "answer" to avoid any confusion.
The current Procedure is :-
CREATE DEFINER=`root`#`localhost` PROCEDURE `user_GetUserInRole`(
IN email nvarchar(256),
IN rolename nvarchar(256),
OUT returnstatus int)
BEGIN
SELECT #UserId := UserId FROM server.`user_data` WHERE EMail = email;
SELECT #RoleId := RoleId FROM server.`user_roles` WHERE RoleName = rolename;
SELECT #this_count := COUNT(*) FROM server.`user_usersinroles` WHERE UserId = #UserId AND RoleId = #RoleId;
IF (#this_count > 0) THEN
SET #returnstatus = 1;
ELSE
SET #returnstatus = 0;
END IF;
END
This is launched by the php :-
$command = "CALL user_GetUserInRole (?, ?, ?)";
$role = "Admin";
$stpro = $conn->prepare($command);
$stpro->bindParam(1, $_SESSION['vaild_user']);
$stpro->bindParam(2, $role);
$stpro->bindParam(3, $returnvalue, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$success = $stpro->execute();
if($success)
{
$returnvalue = $stpro->fetch(PDO::FETCH_ASSOC);
}
If I remove the OUT returnstatus int from the Procedure and the third parameter from the php it runs perfectly and if I add an Insert command for debug purposes in the procedure I am getting the correct answers from the queries.
However, as soon as the OUT is returned to the statement the whole thing falls over and $success = $stpro->execute(); returns "false" every time.
Okay, so in case anyone else runs into this problem, I finally have the answer. The problem is that PDO does not allow you to bind parameters to OUT variables properly. As a result you need to run two queries in order for the CALL to run properly. This allows the variable to be read though the $output arrange and away you go.
$role = "Admin";
$command = "CALL user_GetUserInRole ('" . $_SESSION['vaild_user'] . "', '" . $role . "', #returnvalue)";
$conn->query($command);
$output = $conn->query("SELECT #returnvalue")->fetch(PDO::FETCH_ASSOC);
if ($output["#returnvalue"] == 1)
{
$admin = true;
}
PDOStatement::execute will return a boolean value based on success or failure of the stored procedure call.
So $returnvalue is not really what you think, try this instead:
$command = "EXEC test ?";
$param = "123";
$stpro = $conn->prepare($command);
$stpro ->bindParam(1, $param, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 12);
$success = $stpro->execute();
if($success){
$returnvalue = $stpro->fetch(PDO::FETCH_ASSOC);
var_dump($returnvalue);
}else{
echo "execute() failed!";
}
I am working on a friend list function and I can't figure out how to correctly receive the values.
My code looks like this:
$getuid = $mysqli->prepare("SELECT `uid` FROM `users` WHERE name = ? OR name = ?");
$getuid->bind_param("ss", $user, $friend);
$getuid->execute();
$getuid->bind_result($uid);
$getuid->fetch();
$getuid->close();
$resetpass = $mysqli->prepare("INSERT INTO `friendlist` SET `friend1`=?, `friend2`=?, `accept`=0");
$resetpass->bind_param("ss", $uid[0], $uid[1]);
With the first query I get exactly two uid values back. I want to use them in the second query. It seems like bind_result is not working, neither as array nor when using two values in bind_result. How can I do this using mysqli. I can't use get_result because I'm on PHP 5.2 .
Anyone able to help me?
I think you need something like this. I have not tested it and there are probably even better ways to do this. I just tried the quickest change i could make to your original code to get it to work.
$query = "SELECT uid FROM users WHERE name = '".$user."' OR name = '".$friend."'";
$getuid = $mysqli->query($query);
if($uid = $getuid->fetch_assoc())
{
$query = "INSERT INTO friendlist SET friend1= '".$uid['uid'][0]."', friend2='".$uid['uid'][1]."', accept=0";
$mysqli->query($query)
}
$getuid->close();
Okay I finally understood the concept of fetch.
In order to receive all the values I have to retrieve them in a while-loop.
Here is the solution:
$getuid = $mysqli->prepare("SELECT `uid` FROM `users` WHERE name = ? OR name = ?");
$getuid->bind_param("ss", $user, $friend);
$arra = array();
$getuid->execute();
$getuid->bind_result($uid);
while ($getuid->fetch()) {
$arra[] = $uid;
}
Now I can call the array values using $arra[0] and $arra[1]
I want to edit a table from my database.That table have many data.
I will show sample.Do I need to write many mysql update statement?Have other method to write a only one statement? I am beginner for php? Thank all my friend.Sorry for my english.
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle1',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext1',
WHERE `id` ='$id1';");
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle2',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext2',
WHERE `id` ='$id2';");
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle3',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext3',
WHERE `id` ='$id3';");
etc.............
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle30',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext30',
WHERE `id` ='$id30';");
You want to update multiple rows from one table with specific data, so bad news you have to do it one by one.... but you can improve your code. If I where you I will create a function and I just call it, something like
function update_my_data($movilefilltex1,$id1){
mysql_query("UPDATE `mytablename` SET `mobiletitle` = '$mobiletitle1',
`mobilepublished` = '1',
`mobiletext` = '$mobilefulltext1',
WHERE `id` ='$id1';");
.......
}
So to make the multiple insert you can call update_my_data(value1,valu2) the times that you need. for example in a loop or just whenever you need it.
If there is a UNIQUE index on id (and there will be if it's your PRIMARY KEY), you could use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO mytablename (id, mobiletitle, mobilepublished, mobiletext) VALUES
('$id1', '$mobiletitle1', 1, '$mobilefulltext1'),
('$id2', '$mobiletitle2', 1, '$mobilefulltext2'),
-- etc.
ON DUPLICATE KEY UPDATE
mobiletitle = VALUES(mobiletitle),
mobilepublished = VALUES(mobilepublished)
mobiletext = VALUES(mobiletext);
Note that this will, of course, insert new records if they don't already exist; whereas your multiple-UPDATE command approach will not (it would raise an error instead).
In either case, you could build/execute the SQL dynamically from within a loop in PHP.
I would also caution that you would be well advised to consider passing your variables to MySQL as parameters to a prepared statement, especially if the content of those variables is outside of your control (as you might be vulnerable to SQL injection). If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Putting it all together (using PDO instead of the deprecated MySQL extension that you were using):
for ($i = 1; $i <= 30; $i++) {
$sqls[] = '(?, ?, 1, ?)';
$arr[] = ${"id$i"};
$arr[] = ${"mobiletitle$i"};
$arr[] = ${"mobilefulltext$i"};
}
$sql = 'INSERT INTO mytablename (id, mobiletitle, mobilepublished, mobiletext)
VALUES
' . implode(',', $sqls)
. 'ON DUPLICATE KEY UPDATE
mobiletitle = VALUES(mobiletitle),
mobilepublished = VALUES(mobilepublished)
mobiletext = VALUES(mobiletext)';
$db = new PDO("mysql:dbname=$db", $user, $password);
$qry = $db->prepare($sql);
$qry->execute($arr);
Note that you might also consider storing your 1..30 variables in arrays.
update table1,table2 SET table1.column1 = 'valueX',table2.coulumn2 = 'valueX' where table1.column = table2.coulumn2 ;