I have problem populating table from MySQL to another MySQL table
I read it from one table and then it is fine
when a surname like O'Brian
when I update another table all update exept the O' Brian or any name or surname with the ' in it al through PHP
Ok Here is complete code
$STH2 = $this->run_query("SELECT `member_id`,`first_name`,`last_name` FROM `member_data` WHERE `member_id` = '".$evi."'");
$foundme=0;
while ($rowtop = $STH2->fetch())
{
$foundme++;
$first_name = $rowtop['first_name'];
$last_name= $rowtop['last_name'];
}
$q = $this->update("
UPDATE `users`
SET
`first_name` = '".$first_name."',
`last_name` = '".$last_name."',
Well, if you use PDO try this :
$bdd = /* your database connexion */
$sql = "UPDATE `user`
SET `first_name` = :first_name, `last_name` = :last_name
WHERE `member_id` = 2001;";
$req = $bdd->prepare($sql);
$req->bindParam(':first_name', $first_name);
$req->bindParam(':last_name', $last_name);
$req->execute();
If you don't use PDO, the syntax may differ but the logic should be the same just adapt :
Create the query with some 'param', here :first_name and :last_name
Prepare your query
Bind the param with the actual value, here $first_name and $last_name
Then execute the query
Is it what you are looking for?
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
<?php
session_start();
$con = mysqli_connect("localhost","root","12369","medical");
$data1 = $_SESSION["symp1"];
$data2 = $_SESSION["symp2"];
$data3 = $_SESSION["symp3"];
$data4 = $_SESSION["symp4"];
$finalData = implode(' ', array($data1, $data2, $data3, $data4));
$userinput = $_REQUEST["answer"];
$dname=$_SESSION["dname"];
$dname = str_replace(' ', '_', $dname);
echo $dname." <br>";
$sql = " UPDATE diseases SET UserInput = $finalData WHERE Name = $dname ";
if($userinput=='yes'){
if(mysqli_query($con,$sql)){
echo "Values inserted";
$_SESSION["info"] = "yes";
header('Location: http://localhost/medical/last.php');
}else{
echo mysqli_errno($con);
$_SESSION["info"] = "no";
//header('Location: http://localhost/medical/last.php');
}
}
?>
I'm getting error 1064? I already read answers to similar question, but my code doesn't work. My table schema is:
CREATE TABLE IF NOT EXISTS `diseases` (
`ID` int(50) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) NOT NULL,
`Symptoms` varchar(255) NOT NULL,
`Medicines` varchar(255) NOT NULL,
`Description` varchar(255) NOT NULL,
`Tags` varchar(255) NOT NULL,
`UserInput` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
)
What's wrong in my code? Thanks
Change:
$sql = " UPDATE diseases SET UserInput = $finalData WHERE Name = $dname ";
to:
$sql = "UPDATE `diseases` SET `UserInput` = '$finalData' WHERE `Name` = '$dname'";
Add single quotes around variables that contain a string.
Add backticks around columns and table to prevent mysql reserved words error
It would be even better to use mysqli_prepare do the following:
$stmt = mysqli_prepare($con, "UPDATE `diseases` SET `UserInput` = ? WHERE `Name` = ?");
mysqli_stmt_bind_param($stmt, "ss", $finalData, $dname);
mysqli_stmt_execute($stmt);
As the error message should state, you have an error in your SQL syntax:
MySQL Error 1064: You have an error in your SQL syntax
Surround your data by single quotes and you are good to go. Furthermore, Name is a reserved keyword in MySQL. You can still use it in your query, though, but you should consider escaping table names with backticks:
$sql = " UPDATE diseases SET `UserInput` = '$finalData' WHERE `Name` = '$dname' ";
Add single qoutes around your data:
$sql = " UPDATE diseases SET UserInput = '$finalData' WHERE Name = '$dname' ";
or better use prepared statements
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 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'");
I have a mysql table like this (sql):
CREATE TABLE IF NOT EXISTS silver_and_pgm (
_metal_name varchar(30) NOT NULL,
_bid varchar(30) NOT NULL,
_change varchar(30) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table silver_and_pgm
INSERT INTO silver_and_pgm (_metal_name, _bid, _change) VALUES
('Silver\r\n', '555', '-0.22\r\n'),
('Platinum\r\n', '555', '-9.00\r\n'),
('Palladium\r\n', '555', '0.00\r\n'),
('Rhodium\r\n', '555', '0.00\r\n');
and i am using the following code to update a row which contains metal_name as Silver
<?php
$username = "root";
$password = "1234";
$database = "kitco";
$con=mysql_connect(localhost,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$bid = '101010';
$metal_name = 'Silver';
$query = "update silver_and_pgm set _bid='$bid' where _metal_name='$metal_name'";
//$query2 = "update silver_and_pgm set _bid='444'";;
echo $query."<br>";
$result = mysql_query($query);
if(!$result)echo "error";
?>
but $query doesn't work . it works fine if I use $query2 . If I use the same query directly in SQL of phpmyadmin result is same.
what is the problem with $query . I think its correct.
Would anybody please find the bug ??
It looks like you have a line break in your _metal_name in the database, the SQL query says Silver\r\n.