Roleback CREATE TABLE using MySql Transactions - php

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.

Related

INSERT & CREATE TABLE doesn't seem to be working

I'm currently experiencing some problems.
Basically, I use PDO and I want to create a table and insert some stuff into the table.
I've tried searching for solutions, but it doesn't seem like anything is working.
Please take a look at this:
public function install()
{
global $con;
$sql = "CREATE TABLE if not exists users
(id INT(11) PRIMARY_KEY,
uname VARCHAR(30) ,
pass VARCHAR (40))";
$sq = $con->query($sql);
if ($sq)
{
echo "Table successfully created!";
}
else
{
$this->errors[] = 'Error creating table: users';
}
$sql_code = "INSERT INTO users (
`uname`,
`pass` ) VALUES(
`$this->username`,
`$this->password`
)";
$sq1 = $con->query($sql_code);
if ($sql_code)
{
echo "Successfull!";
}
else
{
echo "Error creating admin user!";
}
}
NOTE: The database connection is set in another file called config.php and I've also included the config.php file to the code.
Well, there could be plenty of things going on, perhaps at the same time.
Maybe your database connection is failing (I'd recommend passing the connection $con by reference to the function install rather than using the global keyword).
Maybe you don't have enough rights to create a table in the database.
Also you are not binding your parameters, this would be the correct way to do it:
$sql_code = "
INSERT INTO users (
uname,
pass
)
VALUES (
:userName,
:password
);
";
$sq1 = $con->prepare($sql_code);
$sq1->bindParam(':userName', $userName);
$sq1->bindParam(':password', $password);
$sq1->query($sql_code);

Issues with when writing to database

I'm unable to write to my database while using this script that I whipped up earlier.
<?php
include("db.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Data sent from form, then posted to "admin" table in database
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$author = mysql_real_escape_string($_POST['author']);
$image = mysql_real_escape_string($_POST['image']);
$category = mysql_real_escape_string($_POST['category']);
$sql = "INSERT INTO admin(name,description,author,image,category) VALUES('$name','$description','$author','$image','$category');";
$result = mysql_query($sql);
header("Location: video.php?file=' . $filename . '");
}
?>
And here's my SQL:
CREATE TABLE admin
(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) UNIQUE,
description VARCHAR(50) UNIQUE,
author VARCHAR(50) UNIQUE,
image VARCHAR(50) UNIQUE,
category VARCHAR(50) UNIQUE
);
Everything is submitted with POST via an HTML form. I'm not really sure what I'm doing wrong, so that why I'm wondering what you guys think. Any thoughts?
$result = mysql_query($sql) is not valid (no connection specified).
It needs to be $result = mysql_query($sql, [CONNECTION]);
There may be other issues, but that's an obvious one.
Follow these steps:
Open a MySQL connection (if not omitted in the snippet)
Check your MySQL statement by using var_dump($sql)
Check for the return value of mysql_query(), should be true if the INSERT statement succeeded.
Check for the number of rows affected by the INSERT statement: mysql_affected_rows()
Note:
I'm pretty sure that your INSERT statement fails because all your columns are defined as UNIQUE. As soon as you already have an author with the same name the statement fails!
$auhtor=mysql_real_escape_string($_POST['author']);
The Author variable is spelled wrong.

mysql update query (containing 'where' syntax) not working

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.

PHP/MYSQL - Check whether it have duplicated record before inserting new record

Suppose I have a table called "device" as below:
device_id(field)
123asf15fas
456g4fd45ww
7861fassd45
I would like to use the code below to insert new record:
...
$q = "INSERT INTO $database.$table `device_id` VALUES $device_id";
$result = mysql_query($q);
...
I don't want to insert a record that is already exist in the DB table, so how can I check whether it have duplicated record before inserting new record?
Should I revise the MYSQL statement or PHP code?
Thanks
UPDATE
<?php
// YOUR MYSQL DATABASE CONNECTION
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'device';
$table = 'device_id';
$db_link = mysql_connect($hostname, $username, $password);
mysql_select_db( $database ) or die('ConnectToMySQL: Could not select database: ' . $database );
//$result = ini_set ( 'mysql.connect_timeout' , '60' );
$device_id = $_GET["device_id"];
$q = "REPLACE INTO $database.$table (`device_id`) VALUES ($device_id)";
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Since I understood well your question you have two ways to go, it depends how you would like to do the task.
First way -> A simple query can returns a boolean result in the device_id (Exists or not) from your database table. If yes then do not INSERT or REPLACE (if you wish).
Second Way -> You can edit the structure of your table and certify that the field device_id is a UNIQUE field.
[EDITED]
Explaining the First Way
Query your table as follow:
SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'
then if you got results, then you have already that data stored in your table, then the results is 1 otherwise it is 0
In raw php it looks like:
$result = mysql_query("SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'");
if (!$result)
{
// your code INSERT
$result = mysql_query("INSERT INTO $database.$table `device_id` VALUES $device_id");
}
Explaining the Second Way
If your table is not yet populated you can create an index for your table, for example go to your SQL command line or DBMS and do the follow command to your table:
ALTER TABLE `your_table` ADD UNIQUE (`device_id`)
Warning: If it is already populated and there are some equal data on that field, then the index will not be created.
With the index, when someone try to insert the same ID, will get with an error message, something like this:
#1062 - Duplicate entry '1' for key 'PRIMARY'
The best practice is to use as few SQL queries as possible. You can try:
REPLACE INTO $database.$table SET device_id = $device_id;
Source

PHP + MySQL is complicated

I am using XMAPP and MySQL is running as it should. In phpMyAdmin, I don't really get the point so I tried creating one in PHP. With this code it tells me the database benutzer. benutzer doesn't exists although I created one in phpMyAdmin and in this code:
<?php
$connect = mysql_connect("127.0.0.1","root","") or die ("Alles scheisse!");
$db = mysql_select_db("benutzer") or die ("Keine benutzer!");
$sql = "CREATE TABLE 'benutzer'
id VARCHAR(100),
name VARCHAR(100),
mail VARCHAR(100),
points INT(1000)
)";
$sql = "INSERT INTO benutzer(`id` , `name` , `mail` , `points`)VALUES(NULL , 'Liam', 'liam#mail.com', '100');";
$db_erg = mysql_query($sql)
or die("Anfrage fehlgeschlagen: " . mysql_error());
?>
Have you also created a table "benutzer" inside db "benutzer"? Your code does not execute your first SQL statement "CREATE TABLE.." so there will be no table "benutzer" if you don't have one created in phpmyadmin.
Did you created the database under the root user? Because you are connecting to the root in your code.

Categories