QUERY 1:
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('rems', $link);
mysql_query('SET AUTOCOMMIT=0; START TRANSACTION', $link);
mysql_query('DELETE FROM admins WHERE admin_id=4', $link);
mysql_query('ROLLBACK; SET AUTOCOMMIT=1', $link);
QUERY 2:
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('rems', $link);
mysql_query('SET AUTOCOMMIT=0;START TRANSACTION;
DELETE FROM admins WHERE admin_id=4;
ROLLBACK; SET AUTOCOMMIT=1', $link);
From the above two queries the first one does not execute properly (transaction does not work) because of executing the queries separately by calling the mysql_query functions multiple times. But i need it do be done by this way. That is i need the result by the first way (calling mysql_query function several times for a single transaction)
Any IDEA please???
With the standard mysql module, either call every query seperately:
mysql_query('SET AUTOCOMMIT=0');
mysql_query('START TRANSACTION');
mysql_query('DELETE FROM admins WHERE admin_id=4');
mysql_query('ROLLBACK');//nothing will be done, I assume it's for testing
mysql_query('SET AUTOCOMMIT=1');
Or create a procedure first:
DELIMITER //
CREATE PROCEDURE weirdrolledbackdelete (IN oid INTEGER)
BEGIN
SET AUTOCOMMIT=0;
START TRANSACTION;
DELETE FROM admins WHERE id = oid;
ROLLBACK;
SET AUTOCOMMIT=1;
END;//
So you can use it later:
mysql_query('CALL weirdrolledbackdelete(4);');
Related
I use PDO in my php framework (flight) and i have a ridiculous problem.
When i insert 1 row into the mysql i saw 3 rows inserted .
Flight::db()->query("INSERT INTO `menu_item`(`order`, `menu_cat_id`) VALUES (22,1)");
This is My whole code :
<?php
require 'flight/Flight.php';
Flight::register('db', 'PDO', array('mysql:host=localhost;port=3306;dbname=deliman', 'root', ''), function($db) {
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
$db->exec("SET NAMES 'utf8';");
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);
});
Flight::route('/menu/item/new', function(){
//$conn = Flight::db();
$data = Flight::db()->query("INSERT INTO `menu_item`(`order`, `menu_cat_id`) VALUES (22,1)");
//SET #maxOrder := (SELECT `order` FROM `menu_item` WHERE `menu_cat_id` = 1 ORDER BY `order` DESC LIMIT 1) +1 ;
//SELECT LAST_INSERT_ID() AS id;
echo 'a';
});
Flight::start();
?>
i find my answer in this post .
pdo insert two rows when I wanna insert only one
So when i test in my browser , it send multiple request and every time my code running . That's it.
I want to insert data in mysql database.when i am trying to insert my query using PHP MyAdmin then work but if i am tring to insert from my php site from submission the not work some text not insert.
my text
http://www.lexisnexis.com/hottopics/gacode/
§ 16-11-125.1. Definitions
As used in this part, the term:
my form submission insert only this text
http://www.lexisnexis.com/hottopics/gacode/
my query
$test='http://www.lexisnexis.com/hottopics/gacode/
§ 16-11-125.1. Definitions
As used in this part, the term:';
$conn = mysql_connect('localhost', 'test', 'test') or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
mysql_query('SET NAMES utf8');
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET SESSION collation_connection ='utf8_unicode_ci'");
$queryc = "INSERT INTO `table` (data17)values ('".addslashes($test)."')";
mysql_query($queryc) or die(mysql_error());
for the database connection, it should be:
$conn = mysqli_connect('localhost', 'test', 'test') or die(mysqli_error($conn));
for the query, it should be:
mysqli_query($conn, $queryc) or die(mysqli_error($conn);
remember, the mysqli_query's arguments are database connection, query
also, it would be better if the query ($queryc) was:
$queryc = "INSERT INTO `table` (data17)values mysqli_real_escape_string($test))";
I have 2 sql queries to execute, but I want it to execute all or if error in one query then dont execute any. I'm using php. I used to use try and catch in .NET but I'm new to php.
Below is the code which i was trying to do:
function Registration($UserFirstname,$UserLastname){
$sql="INSERT INTO table1 (fieldname1,fieldname2) VALUES ('$UserFirstname','$UserLastname')";
$res=mysql_query($sql) or die(mysql_error());
$sql="INSERT INTO table2 (fieldname1,fieldname2) VALUES ('$UserFirstname','$UserLastname')";
$res=mysql_query($sql) or die(mysql_error());}
The problem you're probably facing with try...catch is that PHP has two different error handling mechanisms: error reporting and exceptions. You cannot catch exceptions unless the underlying code throws them and good old mysql_query() will trigger warnings rather than throwing exceptions. There're several workarounds but, if you are interested in writing good object-oriented code, I suggest you switch to PDO.
In any case, if you want to stick to good old MySQL library, your code should basically work:
$res=mysql_query($sql) or die(mysql_error());
The explanation:
mysql_query() returns FALSE if the query fails (e.g., you get a duplicate key)
The right side of the or expression will only execute if the left side is FALSE
die() aborts the script, thus preventing the next queries to be executed
However, I presume that you don't want to abort in the middle of nowhere. If we add some missing bits (such as proper SQL generation and code indentation) we get this:
function Registration($UserFirstname,$UserLastname){
$sql = sprintf("INSERT INTO table1 (fieldname1,fieldname2) VALUES ('%s','%s')";
mysql_real_escape_string($UserFirstname),
mysql_real_escape_string($UserLastname)
);
$res = mysql_query($sql);
if( !$res ){
return FALSE;
}
$sql = sprintf("INSERT INTO table2 (fieldname1,fieldname2) VALUES ('%s','%s')";
mysql_real_escape_string($UserFirstname),
mysql_real_escape_string($UserLastname)
);
$res = mysql_query($sql);
if( !$res ){
return FALSE;
}
return TRUE;
}
About transactions
Please note that you still need to use transactions if there's a chance that the second query fails. Transactions are not particularly difficult to use, the only requirements are:
Define the involved tables as InnoDB
Run a START TRANSACTION query on top of the function
Run a COMMIT query at the end of the function
You need to be using transactions. These allow you to wrap a set of queries in a block that says "Either all these queries execute successfully or none of them do". This means that no matter what happens in the transaction block, you can be sure that the integrity of your database has been maintained.
NOTE: Transactions don't work with MyISAM tables, you have to use InnoDB tables.
mysql_query ('BEGIN TRANSACTION;', $db);
mysql_query ("INSERT INTO sometable (some, columns) VALUES ($some, $values)", $db);
if ($errMsg = mysql_error ($db))
{
mysql_query ('ROLLBACK;', $db);
die ($errMsg);
}
mysql_query ("INSERT INTO someothertable (some, other, columns) VALUES ($some, $other, $values)", $db);
if ($errMsg = mysql_error ($db))
{
mysql_query ('ROLLBACK;', $db);
die ($errMsg);
}
mysql_query ('COMMIT', $db);
You can try to use mysqli_multi_query
Or you can change your DB schema to InnoDB..
For executing two queries as one, you have to use mysql extension, my below code works well
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
See the code below, there are two databases connections.
First it get the data from first connection and then insert into second database connection but it will not insert - I can an error saying Unknown column 'fullname' in 'field list'
When I tried SQL query manually in phpMyAdmin and it work fine...
$db_new = mysql_connect('localhost', 'root', 'password');
if (!mysql_select_db("menu_new", $db_new)) {
die("Cant connect menu_new DATABASE");
}
$db_old = mysql_connect('localhost', 'root', 'password');
if (!mysql_select_db("old_menu", $db_old)) {
die("Cant connect old_menu DATABASE");
}
$SQL_old = "SELECT * FROM old_table";
$q = mysql_query($SQL_old, $db_old);
while ($row = mysql_fetch_assoc($q)) {
$name = $row['name'];
$SQL = "INSERT INTO tbl_name (fullname) values ('$name')";
//Problem Here - It wont insert into second database
mysql_query($SQL, $db_new) or die(mysql_error($db_new));
}
Nothing is strange in this behavior. Just add the $link parameter on your mysql_connect calls, and set it to true. By default it is False and it means that reusing this function with the same parameters, which is what you're doing as the db name is not on your mysql-connect, will reuse existing connexion with same parameters. So you have two variables but only one connexion.
It means you're simply moving the db used in this connexion. Prefixing with the db name fixed the problem as MySQL allow inter-base manipulations from the same connexion if it's on the same db server.
Thanks #Konerak for suggestion and that does work!
To Insert/Select data from Database connection, you will have to include database name before the table name.
For Example
From:
mysql_query("INSERT into tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new));
To:
mysql_query("INSERT into menu_new.tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new));
That is really odd though.
I need to perform a simply query.
Literally, all I need to perform is:
SELECT price, sqft, zipcode FROM homes WHERE home_id = X
When I use PHP PDO, which I've read is the recommended way to connect to a MySQL database, simply creating the connection takes a measured 610ms.
My code is below:
try {
$conn_str = DB . ':host=' . DB_HOST . ';dbname=' . DB_NAME;
$dbh = new PDO($conn_str, DB_USERNAME, DB_PASSWORD);
$params = array();
$sql = 'SELECT price, sqft, zipcode FROM homes WHERE home_id = :home_id';
$params[':home_id'] = X;
$stmt = $dbh->prepare($sql);
$stmt->execute($params);
$result_set = $stmt->fetchAll(PDO::FETCH_ASSOC);
// json output
ob_start("ob_gzhandler");
header('Content-type: text/javascript; charset=utf-8');
print "{'homes' : ";
print json_encode( $result_set );
print '}';
ob_end_flush();
$dbh = null;
} catch (PDOException $e) {
die('Unable to connect');
}
Question: What's the fastest way for me to connect to my MySQL database to perform the query above?
If the slowness is due to having to reach over the network for each connection, and mysql having to do a reverse DNS lookup to check through its GRANTs table, then that overhead could very well account for a large chunk of the latency. Switching to persistent connections would make it a one-time cost for the life of the connection.
However, this does lead to othe problems. Since transactions are rolled back and locks released when the connection holding them is closed, going persitent means they'll stay active. Without taking great care in your code to not leave the connection in an inconsistent state, you could very well create a deadlock or at least lock out all other connections until you go in manually and clean up.
Fastest possible :
mysqli_connect("servername", "user", "pass") or die("can't connect");
mysqli_select_db("dbname") or die("can't select database");
list($price, $sqft, $zipcode) = mysqli_fetch_array(mysqli_query("SELECT price, sqft, zipcode FROM homes WHERE home_id = ".mysqli_real_escape_string($home_id)));
[EDIT]: Now using mysqli instead of mysql.
Guess PDO is as fast as MYSQLI.
I think your problem is how you connect with PDO.
Propably your connectionstring looks like:
:host=localhost;:dbname=foo
And there is the problem... PDO tries to connect to localhost but PDO uses the DNS to turn localhost into 127.0.0.1 and this is what costs time.
If you use 127.0.0.1 directly you wont have these problems anymore :)
So the connectionstring must look like
:host=127.0.0.1;:dbname=bar
as of version php 5.3.0 the fastest and most lightweight way of calling into the db from php is as follows:
This example uses the mysql/ext (not mysqli) and calls stored procedures
$conn = mysql_connect("localhost", "user", "pass");
mysql_select_db("db");
$sql = sprintf("call get_user(%d)", 1);
$result = mysql_query($sql);
mysql_free_result($result);
mysql_close($conn);
The stored procedure:
delimiter #
create procedure get_user
(
in p_user_id int unsigned
)
begin
select
u.user_id, u.username, u.status_id, s.name as status_name, ...
from
users u
inner join user_status s on u.status_id = s.status_id
...
where
u.user_id = p_user_id;
end #
delimiter ;