I am trying to enter into a table in with PDO if using an if condition. My code for the function is below:
function add_user_info($conn, $user, $info, $fName, $sName, $past, $pos){
// Prepare and execute statements
$info1 = addslashes($info);
$sql = $conn->prepare("SELECT * FROM `User_Info` WHERE `User` = '$user'");
$sql->execute();
if ($sql->fetch()){
// Update current entry
$sql1 = $conn->prepare("UPDATE `User_Info` SET `Info` = '$info1' AND `Past` = '$past' AND `Position` = '$pos' WHERE `User` = '$user'");
} else {
// Create new entry
$sql1 = $conn->prepare("INSERT INTO `User_Info` (`User`, `Info`, `FName`, `SName`, `Past`, `Position`) VALUES ('$user', '$info1', '$fName', '$sName', '$past', '$pos')");
}
$sql1->execute();
}
The ONLY (I repeat, ONLY) part that is not working for me is on line 9 with the update query. I have narrowed the problem down to it being related with the update of the Info column, and not only that but it is a problem with the string so the variable $info1.
I am trying to pass in a string of text from CKEditor. It is a rich text string and so has HTML tags, quotations, etc in it when passed to the SQL.
The initial creation of the row in the table (line 12 of the function) works PERFECTLY so it is only on the update that the string is seen as funny. When I update with a word in place of $info1 it still does not work.
As shown in phpmyadmin, my table schema is as follows:
Update command multiple set is separated by , not and
UPDATE `User_Info`
SET
`Info` = '$info1' ,
`Past` = '$past' ,
`Position` = '$pos'
WHERE `User` = '$user'"
Change AND to ,
$sql1 = $conn->prepare("UPDATE `User_Info` SET `Info`='$info1', `Past`='$past', `Position`='$pos' WHERE `User`='$user'");
Related
I'm setting up a simple website where each user gets their own table (bad idea, I know), in which other users can put comments into - like a super budget version of a Facebook-wall.
This is what my query looks like when I create the table:
$userTable = mysqli_query($conn, "CREATE TABLE `".$epost."`(
ID INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
eMail VARCHAR(50) NOT NULL,
comment VARCHAR(500) NOT NULL,
timestampp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
)");
However, when I try to take the values from a form, and insert them into the specific table they can't seem to find their way in there. Here's my code of that:
<?php
include 'connect.php';
/*if(isset ($_POST['userUser']))*/
$valueEmail = mysqli_real_escape_string($conn, $_POST['userEmail']);
$valueUser = mysqli_real_escape_string($conn, $_POST['userUser']); /*have the user to input the name, so i can connect to the correct DB*/
$valueMessage = mysqli_real_escape_string($conn, $_POST['userMessage']);
$findUserTable = "SELECT * FROM UserInfo WHERE Firstname = '$valueUser'";
$findUserEmail = mysqli_query($conn, $findUserTable);
if(mysqli_num_rows($findUserEmail) > 0) /*finding the name of the persons email*/
{
while ($result = mysqli_fetch_assoc($findUserEmail))
{
$email = $result['Email'];
}
}
/* VALIDATION HERE */
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
header("refresh:10 url=userProfil.php");
/*echo '<script>alert("Meddelande skapat!");</script>';*/
echo $sql;
mysqli_close($conn);
?>
I've been trying different 'versions' of the variable, like ".$email.", '.$email.' and ".$epost.". I get the correct name when i echo out my query or just the variable - but it can't seem to find the table?
I'm very aware that my code smells badly, so please spare me on that point.
You just simple write your query forget to execute it.
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES ('$valueEmail', '$valueMessage')"; /* wrong query?*/
Use this
mysqli_query($conn,$sql);//for execute
Better use Bind and prepare statement as
$sql = "INSERT INTO ".$email." (eMail, comment) VALUES (? ,?)"; /* wrong query?*/
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $valueEmail, $valueMessage);
/* Execute the statement */
$stmt->execute();
$row = $stmt->affected_rows;
if ($row > 0) {
echo "data inserted";
} else {
"error";
}
Read http://php.net/manual/en/mysqli-stmt.bind-param.php
So I'm using php to add or get data from a database. The way I'm trying to do this is to check if there is something there with that title, if there is, edit it, if not, add a new entry. This is the code I'm using:
$SQL_CHECK = "SELECT * FROM `doc`.`appointment` WHERE `title` = '$form_title';";
$checkQ = $con->query($SQL_CHECK);
if(mysqli_num_rows($checkQ)>=1) {
while($t = mysqli_fetch_array($checkQ)){
$editID = $t['id'];
//edit the entry
$query_edit = "UPDATE `doc`.`appointment` SET `title`='$form_title' WHERE `id`=$editID;";
$edit_row = $con->query($query_edit);
}
}elseif(mysqli_num_rows($checkQ)==0){
//add new entry
$query1 = "INSERT INTO `doc`.`appointment` (`start`, `end`, `title`, `body`) VALUES ('$start_date', '$end_date', '$form_title', '$form_body');";
$result1 = $con->query($query1);
}
The problem I have is that, when I run the code, if there already is something there, it runs both queries (it adds a new one and edits the one existing)
I have seen and read a few questions about this but I can't figure out what's going on. I have a SP that inserts into a table and then returns just a single column with the last inserted id(Since I'm executing multiple statments lastInsertID() doesn't work.
CREATE DEFINER=`graffixnyc`#`%` PROCEDURE `createUser`(
IN userName VARCHAR(50),
IN firstName VARCHAR(25),
IN lastName VARCHAR(25),
IN pass text)
BEGIN
SELECT FLOOR(RAND() * 0xFFFFFFFF) into #salt;
INSERT INTO `users` (`username`, `first_name`,`last_name`,`salt`,`password`)
VALUES (userName, firstName,lastName, (select
#salt),sha2(concat(md5(pass(select #salt)),256));
SELECT LAST_INSERT_ID() as lastinsert;
END
Now when I execute this is MySql is returns the value of the last inserted record. When I try to access it with PHP I get Null.
$paramUsername = $req->params('username'); // Getting parameter with names
$paramFirstName = $req->params('firstname');
$paramLastName = $req->params('lastname');
$paramPassword = $req->params('password');
$sql = "CALL createUser(:username, :firstname,:lastname,:password)";
try {
$dbCon = getConnection();
$stmt = $dbCon->prepare($sql);
$stmt->bindParam("username", $paramUsername);
$stmt->bindParam("firstname", $paramFirstName);
$stmt->bindParam("lastname", $paramLastName);
$stmt->bindParam("password", $paramPassword);
$stmt->execute();
$row= $stmt->fetch();
$last_id=$row["lastinsert"];
$user->id =$last_id;
I have also tried using an output Paramater like so:
CREATE DEFINER=`graffixnyc`#`%` PROCEDURE `createUser`(
IN userName VARCHAR(50),
IN firstName VARCHAR(25),
IN lastName VARCHAR(25),
IN pass text,
OUT lastinsert INT)
BEGIN
SELECT FLOOR(RAND() * 0xFFFFFFFF) into #salt;
INSERT INTO `users` (`username`, `first_name`,`last_name`,`salt`,`password`)
VALUES (userName, firstName,lastName, (select
#salt),sha2(concat(md5(pass(select #salt)),256));
SET lastinsert=(SELECT LAST_INSERT_ID());
SELECT lastinsert;
END
$paramUsername = $req->params('username');
$paramFirstName = $req->params('firstname');
$paramLastName = $req->params('lastname');
$paramPassword = $req->params('password');
$sql = "CALL createUser(:username, :firstname,:lastname,:password,
#lastinsert)";
try {
$dbCon = getConnection();
$stmt = $dbCon->prepare($sql);
$stmt->bindParam("username", $paramUsername);
$stmt->bindParam("firstname", $paramFirstName);
$stmt->bindParam("lastname", $paramLastName);
$stmt->bindParam("password", $paramPassword);
$stmt->execute();
$row = $dbCon->query("select #lastinsert;")>fetch();
$last_id=$row["#lastinsert"];
$user->id =$last_id;
When I try it like this I get this error:
{"error":{"text":SQLSTATE[HY000]: General error: 2014 Cannot execute queries
while other unbuffered queries are active. Consider using
PDOStatement::fetchAll(). Alternatively, if your code is only ever going to
run against mysql, you may enable query buffering by setting the
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.}}
So I tried FetchAll and got the same error.. I then tried this which I found here which works but since it's only returning 1 row with 1 feild it doesn't seem like I should really need to loop through anything:
$stmt->execute();
$stmt = $dbCon->prepare("select #lastinsert;");
$outputArray = $dbCon->query("select #lastinsert;")->fetchAll();
foreach($outputArray as $row)
{
$last_id=$row["#lastinsert"];
}
So if there a better way to do this? I'm sure there is. I'm pretty new to PHP and mySQL but have a lot of experience with SQLServer so any insight would be appreciated.
I figured it out.. This works well and I don't need the input paramater or the loop:
SP:
CREATE DEFINER=`graffixnyc`#`%` PROCEDURE `createUser`(
IN userName VARCHAR(50),
IN firstName VARCHAR(25),
IN lastName VARCHAR(25),
IN pass text)
BEGIN
SELECT FLOOR(RAND() * 0xFFFFFFFF) into #salt;
INSERT INTO `users` (`username`, `first_name`,
`last_name`,`salt`,`password`)
VALUES (userName, firstName,lastName, (select #salt),sha2(concat(md5(pass
),(select #salt)),256));
SELECT LAST_INSERT_ID()as lastinsert;
END
PHP:
$paramUsername = $req->params('username');
$paramFirstName = $req->params('firstname');
$paramLastName = $req->params('lastname');
$paramPassword = $req->params('password');
$sql = "CALL createUser(:username, :firstname,:lastname,:password)";
try {
$dbCon = getConnection();
$stmt = $dbCon->prepare($sql);
$stmt->bindParam("username", $paramUsername);
$stmt->bindParam("firstname", $paramFirstName);
$stmt->bindParam("lastname", $paramLastName);
$stmt->bindParam("password", $paramPassword);
$stmt->execute();
$user->id =$stmt->fetchColumn(0);
$dbCon = null;
I'm sending form data to db with UPDATE query:
mysql_query("UPDATE users SET price = '100-200' WHERE login = '$login'");
mysql_query("UPDATE users SET city = '$city' WHERE login = '$login'");
My question is: how to rebuild it to have query which writes data in db, but do not remove older posts.
For example: If user enters data 'price' and 'city', and after this, he wants to change only 'city', script with update will cancel 'price' and leave blank field in db.
How to make it to update (like in example) only city, but to leave price as it was before (100-200). Is there a proper query for this?
You will want to do a check for NULL or empty variables before running the SQL Statements. Something like this:
if(!empty($price))
{
mysql_query("UPDATE `users` SET `price` = '".$price."' WHERE `login` = '".$login."';");
}
if(!empty($city))
{
mysql_query("UPDATE `users` SET `city` = '".$city."' WHERE `login` = '".$login."';");
}
use "INSERT INTO table (column1, column2,column3) VALUES (val1,val2,val3)";
ps: mysql_* is deprecated update to PDO or MySQLi
$sql = "select * from instalmentsdetails_ where studentFeeId='$savestudentfees' AND instalmentName='$instlnamefdtls'";
$query = $this->db->query($sql);
if($query->num_rows() > 0){
echo($id);
$this->db->where('instalmentsDetailsId',$id);
$this->db->update('instalmentsdetails_',$instldata);
}else{
echo($id);
$id='';
echo($id);
$sql= "INSERT INTO instalmentsdetails_` (`instalmentsDetailsId`, `studentFeeId`, `instalmentName`, `amount`, `dueDate`, `status`) VALUES ('$id', '$savestudentfees', '$instlnamefdtls', '$amtfdtls', '2011-10-06', '1')";
$id=$this->db->insert_id();
$query = $this->db->query($sql);
return $query;
}
return $id;
This query first checks if there are any rows present, if there is, it is going to update the old record, otherwise it is going to create a new record, but for some reason it does not work as expected even when the query returns num_row() > 0.It's a model in codeigniter
Have you checked the output of $query->num_rows()?, eg echo $query->num_rows()
You could do this instead and save the bother in PHP
ALTER TABLE teami_db ADD UNIQUE INDEX(studentFeeId, instalmentName);
Then you can perform an ON DUPLICATE KEY UPDATE query like so.
INSERT INTO `instalmentsdetails_teami` (
`instalmentsDetailsId`,
`studentFeeId`,
`instalmentName`,
`amount`,
`dueDate`,
`status`
) VALUES (
'$id',
'$savestudentfees',
'$instlnamefdtls',
'$amtfdtls',
'2011-10-06',
'1'
) ON DUPLICATE KEY UPDATE
`instalmentsDetailsId` = VALUES(`instalmentsDetailsId`),
`studentFeeId` = VALUES(`studentFeeId`),
`instalmentName` = VALUES(`instalmentName`),
`amount` = VALUES(`amount`),
`dueDate` = VALUES(`dueDate`),
`status` = VALUES(`status`)
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html