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.
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?
This query change only the name, I want change the username too...
<?php
define('HOST', 'localhost');
define('USERNAME', 'root');
define('PASSWORD', '');
define('DATABASE', 'mydb');
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
$query = "CREATE TABLE users (id INT UNSIGNED NOT NULL AUTO_INCREMENT, username VARCHAR(50) NOT NULL, name VARCHAR(50) NULL, PRIMARY KEY (id), UNIQUE(username)) ENGINE = MyISAM";
if ($mysqli->query($query)) {
$query = "INSERT INTO users (id, username, name) VALUES (1, 'user1', 'name1')";
if ($mysqli->query($query)) {
$query = "UPDATE users SET username = 'user_1', name = 'name_1' WHERE id = 1";
if ($mysqli->query($query)) {
$query = "SELECT id, username, name FROM users WHERE id = 1";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo 'id = ' . $row['id'] . ', username = ' . $row['username'] . ', name = ' . $row['name'];
}
$result->free();
}
}
}
$mysqli->close();
?>
In this example:
Started as [1, user1, name1]
Changed to [1, user1, name_1]
Instead of [1, user_1, name_1]
There is no way to update UNIQUE columns?
Your script won't run (table creation) when reloading it (only on the first/initial execution), since your table already exists and MySQL is failing on you silently, since you're not checking for errors.
Sidenote: You may have slightly modified your script and then ran it after.
Having included the following debugging code at the top of your script, you would have been thrown errors about it and is crucial when debugging during development before going live:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// rest of your code
Therefore, you can only run that script once. You need to either test it again with a new table name, or remove the table creation code.
You can also check if the table exists.
References:
http://dev.mysql.com/doc/refman/5.7/en/create-table.html
https://dev.mysql.com/doc/refman/5.5/en/replication-features-create-if-not-exists.html
A quick example:
CREATE TABLE IF NOT EXISTS `test`
You can also use UPDATE IGNORE table ... syntax (not to be used with your present table creation codes though):
http://dev.mysql.com/doc/refman/5.7/en/update.html
and INSERT IGNORE INTO table
https://dev.mysql.com/doc/refman/5.5/en/insert.html
Now your entire code (as a rewrite) would look like this:
$query = "CREATE TABLE IF NOT EXISTS users
(id INT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
name VARCHAR(50) NULL,
PRIMARY KEY (id),
UNIQUE(username))
ENGINE = MyISAM";
if ($mysqli->query($query)) {
$query = "INSERT IGNORE INTO users (id, username, name) VALUES (1, 'user1', 'name1')";
if ($mysqli->query($query)) {
$query = "UPDATE IGNORE users SET username = 'user_1', name = 'name_1' WHERE id = 1";
if ($mysqli->query($query)) {
$query = "SELECT id, username, name FROM users WHERE id = 1";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo 'id = ' . $row['id'] . ', username = ' . $row['username'] . ', name = ' . $row['name'];
}
$result->free();
}
}
}
There is no way to update UNIQUE columns?
Yes, with UPDATE IGNORE table ....
http://dev.mysql.com/doc/refman/5.7/en/update.html
However and with your present code, it will fail on the INSERT, since that is being executed before the UPDATE.
Think logically and you will see what is going on here.
<?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'm writing a upgrader for a mysql database using PHP. The behavior of the upgrader should be as follows.
If all the queries executed successfully the changes should be committed.
If a sinngle query get faild eveything should be roled back to previouse state.
Part of my program is as follows.
$host = 'localhost';
$user = 'root';
$password = 'root';
$db = 'transaction';
$con = mysqli_connect($host, $user, $password);
mysqli_select_db($con, $db);
mysqli_autocommit($con, FALSE);
$query1 = "create table `status` (
`id` int not null auto_increment,
`name` varchar(60) not null,
primary key (`id`)
) engine=innodb default charset=utf8;";
$result1 = mysqli_query($con, $query1);
$query2 = "ALTER TABLE status
CHANGE name value varchar(512);";
$result2 = mysqli_query($con, $query2);
if(!($result1 && $result2)) {
mysqli_rollback($con);
} else {
mysqli_commit($con);
}
mysqli_close($con);
But if the 'status' table already exists the first create table query is failing. So both queries should be rolled back. But the alter query has executed and not rolled back.
I saw a post which list all the queries which cannot be rolled back in mysql. http://www.sitepoint.com/mysql-transaction-gotchas-good-parts/
Is there any possible way to do this role back in mysql.
No. You would need to run a new alter table query undoing your previous alter statement.
do it manualy
if(!($result1 && $result2)) {
#drop table
$query1 = "drop table `status`";
$result = mysqli_query($con, $query1);
}
Would it be better to just export the data into (say) a collection of CSV files. Then modify any dataif needed to match the new structure. Then just create the database with the new structure and import the data into it.
Seems a simpler solution that trying to make an upgrader.