<?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
Related
I have table column log_id as primary_key auto_increment.
Do I need to specify it within INSERT INTO statement or no?
I am getting next error while trying to insert values into my database:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(log_session,log_ip,log_vrijeme,log_model) my_log VALUES ('270043ae1526e4' at line 1 INSERT INTO (log_session,log_ip,log_vrijeme,log_model) my_log VALUES ('270043ae1526e44967889b4382ff69fd','93.142.54.135','2018-11-23 14:06:15','1402')
My code is:
<?php
$_SESSION['compare_hash'] = "270043ae1526e44967889b4382ff69fd";
$log_session = $_SESSION['compare_hash'];
$log_ip = $_SERVER['REMOTE_ADDR'];
$log_vrijeme = date("Y-m-d H:i:s");
$log_model = "1402";
$con = mysqli_connect("localhost","user","password","databse");
$sql = "
INSERT INTO (log_session,log_ip,log_vrijeme,log_model) my_log
VALUES ('$log_session','$log_ip','$log_vrijeme','$log_model')
";
$rez = mysqli_query($con, $sql) or die(mysqli_error($con)."<br>$sql");
mysqli_close($con);
?>
Table structure:
Field Type Null Key Default Extra
log_id int(11) NO PRI NULL auto_increment
log_session varchar(42) NO MUL NULL
log_ip varchar(15) NO NULL
log_vrijeme datetime NO MUL NULL
log_model int(11) NO MUL NULL
Thank you for help.
You should put my_log right after INSERT INTO:
<?php
$_SESSION['compare_hash'] = "270043ae1526e44967889b4382ff69fd";
$log_session = $_SESSION['compare_hash'];
$log_ip = $_SERVER['REMOTE_ADDR'];
$log_vrijeme = date("Y-m-d H:i:s");
$log_model = "1402";
$con = mysqli_connect("localhost","user","password","databse");
$sql = "
INSERT INTO my_log (log_session,log_ip,log_vrijeme,log_model)
VALUES ('$log_session','$log_ip','$log_vrijeme','$log_model')
";
$rez = mysqli_query($con, $sql) or die(mysqli_error($con)."<br>$sql");
mysqli_close($con);
?>
However, your code has several drawbacks, I'll describe them a bit later.
1. Don't pass unescaped variables into query
Until you have no other way. Use mysqli_real_escape_string($con, $your_var) to prevent SQL injection and using PDO would make it even better.
2. Use HEREDOC syntax to ensure query consistency during future edits
In this way even if you of someone will put " into query it would still work as expected.
3. Omit closing tag on the end of your PHP files if you don't have any content below
This will prevent surprising errors from happening.
<?php
$_SESSION['compare_hash'] = "270043ae1526e44967889b4382ff69fd";
$con = mysqli_connect("localhost","user","password","databse");
$log_session = mysqli_real_escape_string($con, $_SESSION['compare_hash']);
$log_ip = mysqli_real_escape_string($con, $_SERVER['REMOTE_ADDR']);
$log_vrijeme = mysqli_real_escape_string($con, date("Y-m-d H:i:s"));
$log_model = mysqli_real_escape_string($con, "1402");
$sql = <<<SQL
INSERT INTO my_log (log_session,log_ip,log_vrijeme,log_model)
VALUES ('${log_session}','${log_ip}','${log_vrijeme}','${log_model}')
SQL;
$rez = mysqli_query($con, $sql) or die(mysqli_error($con)."<br>$sql");
mysqli_close($con);
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?
hey i have a problem with inserting some data in my database:
define('SECURE', true);
include "storescripts/connect_to_mysql.php";
$txn_id = 123456789101234567;
$payer_email = "irgendwas#gmx.de";
$mc_gross = "amount";
$sql = "SELECT COUNT(*) AS count FROM `trans` WHERE `txn_id` = $txn_id";
$q = mysqli_query($mysqli, $sql);
$f = mysqli_fetch_array($q);
if($f['count'] > 0) {
echo "Transaction already processed";
} else {
$insert = mysqli_query($mysqli, "INSERT INTO trans (`txn_id`, `payer_email`,`mc_gross`)
VALUES ($txn_id,$payer_email,$mc_gross)");
if($insert = 1) {
echo "inserted";
} else {
echo "not inserted";
}
}
As a result i get: "inserted", but i have no data in my database..anyone can help me? where is the bug?
edit: this is my table:
define('SECURE', true);
require "connect_to_mysql.php";
$sqlCommand = "CREATE TABLE trans (
id int(11) NOT NULL auto_increment,
txn_id varchar(255) NOT NULL,
payer_email varchar(255) NOT NULL,
mc_gross int(255) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY (txn_id))";
if ($mysqli->query($sqlCommand)) {
echo "Your trans table has been created successfully!";
} else {
echo "CRITICAL ERROR;".$mysqli->error;
}
The reason you are getting "inserted" is because your if is setting the variable to 1 and is resulting true. Use double equals to compare.
right:
if ($insert == 1)
wrong:
if ($insert = 1)
As far as your sql there seems to be errors with your queries. $txn_id and $payer_email are both varchars which require you to use quotes since it is a string
The string literals in your SQL statement need to be enclosed in single quotes. Your generated SQL text looks like this:
VALUES (123456789101234567,someone#email.de,amount)
But it should really look like this:
VALUES ('123456789101234567','someone#email.de','amount')
^ ^ ^ ^ ^ ^
BTW... when evaluated as an integer, that string literal 'amount' is going to be interpretted as zero.
You should consider using prepared statements with bind variables, instead of including variables in the SQL text. (There are lots of examples of that on StackOverflow.)
To check whether mysqli_query succeeded or not:
$sql = "INSERT INTO ... ";
if ( mysqli_query($mysqli, $sql) ) {
// sql statement executed without error
} else {
// sql statement execution raised an error
}
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.
I am writting a script that checks a folder K:/Comics and inserts each name + number into a database, table name = comics. Now what i would like to do would be to check to see if this comic already exists before we run the insert queries.
Table Structure:
CREATE TABLE IF NOT EXISTS `comics` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`issue` varchar(4) DEFAULT NULL,
`bio` longtext NOT NULL,
`pages` int(10) NOT NULL,
`size` varchar(100) NOT NULL,
`price` varchar(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;
Code:
<?php
$main_folder = 'K:/Comics/'; // should be K:\Comics\ but I changed it because of the highlighting issue
$folders = glob($main_folder.'* [0-9]*', GLOB_ONLYDIR);
$comics_series = array();
foreach($folders as $folder){
$comics_series[] = preg_split('/(.+)\s(\d+)/', str_replace($main_folder, '', $folder), -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
}
$values = array();
foreach($comics_series as $pair){
$values[] = "('".mysql_real_escape_string($pair[0])."', '".((int) $pair[1])."')";
}
$query = 'INSERT IGNORE INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
?>
What I thought would work but doesn't (still adds comics to the db that are already there):
$query = 'INSERT IGNORE INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
What did I forget?!? The documentation said just to add IGNORE in there and it would work...
<?php
$main_folder = 'K:/Comics/';
$folders = glob($main_folder.'* [0-9]*', GLOB_ONLYDIR);
$comics_series = array();
foreach($folders as $folder){
$comics_series[] = preg_split('/(.+)\s(\d+)/', str_replace($main_folder, '', $folder), -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
}
$values = array();
foreach($comics_series as $pair){
// clean the values to protect against SQL injection
$pair = array(
mysql_real_escape_string($pair[0]),
mysql_real_escape_string($pair[1])
);
// add it to the values array, for insert
$values[] = "('".$pair[0]."', '".$pair[1]."')";
}
$query = 'INSERT INTO comics (name, issue) VALUES '.implode(',', $values).' '.
'ON DUPLICATE KEY UPDATE `issue` = VALUES(`issue`)';
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
?>
mysql_query() returns a result resource, not an integer or set of values or anything else. Try changing
if ($check_query == '0'){
to
if (mysql_num_rows($check_query) == 0){
However, I would probably just use:
INSERT IGNORE INTO ...
Since it probably doesn't matter. Check out the MySQL Insert Syntax for more info.
doesn't work is not too informative.
Use mysql_num_rows instead of == '0', it's really meaningless
There are no surrounding quotes around the $values.
Wrap the values with parentheses
I would place a combined unique index on the name and issue columns of the table to enforce the combination of these values to be distinct within the table.
You could then do the following and not worry about double records:
$query = 'INSERT INTO comics (name, issue) VALUES '.implode(',', $values).'
ON DUPLICATE KEY UPDATE id=id'; //makes sure you don't get an error
You could also use the INSERT IGNORE statement (as stated by #Dereleased) to avoid inserts of duplicates (in the before specified unique index).
Also see the documentation for the ON DUPLICATE KEY UPDATE statement, it might be helpfull in situations where you want to update the record if it was found as a duplicate while inserting.
mysql_query returns a statement handle if the query succeeds, and boolean FALSE if the query fails. You'd need to do:
$check_query_result = mysql_query(...) or die(mysql_error());
if(mysql_num_rows($check_query_result) == 0) {
... comic doesn't exist ...
}
Note that a query returning no rows is NOT a failure condition. It's simply a result that happened to have no rows