SQL query SET & Update but not being called from PHP - php

I'm trying to update table rows to have random numbers. Now I can achieve this using phpMyAdmin and run it via SQL query. However if I try and run the same code via a PHP call then it doesn't work.
Any ideas why this would be the case and how I would correct it?
Table name is: num_image
Column Name: rownum
This is the SQL I'm using:
SET #rownum := 0;
UPDATE num_image SET rownum = (#rownum:=#rownum+1) ORDER BY RAND();
I've tried entering it in my php code as follows:
<?php
// Connect to database
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
// Assigns a new random number with no duplicates to database for each rownum row.
$updaterownum = mysql_query("SET #rownum := 0; UPDATE num_image SET rownum = (#rownum:=#rownum+1) ORDER BY RAND();");
echo 'All rownums have been updated!';
?>
My database connection works fine as I use the same for other database updates and inserts. So I've narrowed it down to how I'm inserting the actual SQL in my PHP call and believe I have to edit the way I call it?
I'm sure it's something minor I have missed, though I'm stumped. Thanks in advance!

I see a document at:
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
Here are some brief lines:
MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.
Multiple statements or multi queries must be executed with mysqli_multi_query(). The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.
The MySQL server allows having statements that do return result sets and statements that do not return result sets in one multiple statement.

The following polished code can do the job in PHP. However, as mentioned in comments; The mysql extension is deprecated and will be removed in the future.
<?php
// Connect to database
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if($con)
{
$updaterownum = mysql_query("SET #rownum := 0");
$updaterownum = mysql_query("UPDATE num_image SET rownum = (#rownum:=#rownum+1) ORDER BY RAND()");
if(mysql_affected_rows()>0)
{
echo 'All rownums have been updated!';
}
else
{
echo "Nothing changed after running update query!";
}
}
else
{
echo "Not able to connect";
}
?>

Related

sql results show up on phpmyadmin but doesn't return records to my website

I have this really basic sql code I've copied over which ranks 10 people's scores, it seems to work fine on the phpmyadmin website, although on my website it returns this message: SQLSTATE[HY000]: General error
My guesses are that this message appears because the SET function doesn't allow for a returning record.
So my solution is to change the SQL code I copied to do the same thing but written differently to work on my website.
Click here to see the SQL code in phpMyAdmin
I know a lot of you will be asking for the php code so here it is.
$servername = "mysql12.000webhost.com";
$username = "corey";
$password = "pass";
$dbname = "database";
$sql = "SQL CODE PLACED HERE. PASTED BELOW";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = new RecursiveArrayIterator($stmt->fetchAll());
echo json_encode($rows);
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
and the SQL code here:
SET #count =0;
SELECT *
FROM (SELECT * , #count := #count +1 AS rank
FROM montsbattlefront
WHERE RacesWon >=0
ORDER BY RacesWon DESC
) AS t
WHERE rank
BETWEEN 0
AND 100000
The PHP code works perfectly fine.
The SQL code is where I have the most issues with.
I tried replacing SET with something else like a BEGIN END to allow for local variables and the usage of SET, although this just opened up more problems than before, since phpmyadmin does not really make support for DELIMITER very clear. Does anybody know a simple solution to write simple SQL code to do what I want to do? I'm not an SQL pro, I just know the basics.
For example instead of using #count, I can use COUNT() or ROW_NUMBER() for some reason ROW_NUMBER also does not work with phpmyadmin. If anyone can find a solution to my basic but huge problem, I will be so happy.
Regards,
Corey S.
Try removing the set statement and then you can initialize the user-defined variable in a subquery instead:
SELECT *
FROM (
SELECT * , #count := #count +1 AS rank
FROM montsbattlefront, (SELECT #count := 0) t
WHERE RacesWon >=0
ORDER BY RacesWon DESC
) AS t
WHERE rank BETWEEN 0 AND 100000

Mysql transaction not working as expected

I have read a lot of documentation about mysql and transactions and from what I have understood is that when I use repeatable read isolation level in MySQL InnoDB and I start a transaction and I add some rows that when I do a select on those rows they aren't seen by MySQL in that transaction. For example:
function dotransaction() {
$result = mysqli_query("START TRANSACTION");
if (!$result) return false;
$result = mysqli_query("INSERT INTO t (f1,f2) VALUES (1,2)");
if (!$result) {
mysqli_query("ROLLBACK");
return false;
}
$result = mysqli_query("INSERT INTO t (f1,f2) VALUES (3,4)");
if (!$result) {
mysqli_query("ROLLBACK");
return false;
}
$result = mysqli_query("UPDATE t2 SET f3=(SELECT COUNT(*) AS count FROM t WHERE f1=1) WHERE f4=2");
if (!$result) {
mysqli_query("ROLLBACK");
return false;
}
}
If i execute the following code in PHP it really updates field f3 to 1 in table t2. But I didn't expect that, because when I started the transaction the transaction reads a snapshot from the database and whereever I use a select statement it uses the first read snapshot and not the modifications to the table. When I take the select statement out of the UPDATE statement it also goves met count=1.
You understand wrong.
Changes to data made within transaction ARE visible within that transaction, so your SELECT statements will see updated rows.
These changes however are not visible outside of the transaction, so if another user connects to the server at the same time, and queries these rows, he will see them in unaltered state.

MySqli not rolling back appropriately

I have a database listed as $db under mysqli. This database is contains into two tables, I listed them below as table and table2 (just for this example). Table2's rows requires an id from table. This is fine, but there might be a problem adding the columns into table2 thus requiring a rollback routine. However, it doesn't seem to be working.
I started with turning off the auto-commit. I then tried to put in the rollback command even though I am using the die command to signal a failure. As far as I am concerned the transaction could be blasted into oblivion in mid operation and the database should still be stable. So I am not sure what is going on here unless the database is completely ignoring the fact that I am trying to turn off auto-commit.
The basic structure of my code is listed below:
function problem($str)
{
global $db;
mysqli_rollback($db);
die($str);
}
mysqli_autocommit($db,false);
//Basic check if exists
$sqlstr = "SELECT * FROM table WHERE name = '$name';";
$r = mysqli_query($db,$sqlstr);
if (mysqli_num_rows($r)>0){problem("A row already exists under that id");}
//Insert the row
$sqlstr = "INSERT INTO table (name,v1,v2,v3) VALUES ('$name','$v1','$v2','$v3');";
$r = mysqli_query($db,$sqlstr);
if (!$r){problem("Could not insert into the table. $sqlstr");}
//Get the generated id part 1
$sqlstr = "SELECT id FROM table WHERE name = '$name';";
$r = mysqli_query($db,$sqlstr);
if (!$r){problem("Could not add into the table. $sqlstr");}
//Get the generated id part 2
$row = mysqli_fetch_assoc($r);
$eid = $row['id'];
//A simple loop
$count = count($questions);
for ($i=1;i<=$count;$i++)
{
//This is where it typically could die.
$r = mysqli_query($db,"INSERT INTO table2 VALUES (...);");
if (!$r){problem("Could not add to the table2. $sqlstr");}
}
mysqli_commit($db);
Is there something I am missing? I tried to follow the examples I found for the auto-commit as closely as I could.
Transactions only work if the table engine supports them, e.g. InnoDB.

mysqli_multi_query function not updating all table rows in database

I have been attempting to use mysqli_multi_query to update multiple table rows at once. I have found that this function always leads to the update of all rows except for 1 row. For instance, if I had 5 rows of data that I designated to be updated, then only 4 rows are actually updated. Even when I increased the numbers of rows to 6 or 7 etc, there is only 'n-1' rows actually updated ('n' being the numbers that I designated to be updated).
some of the code is below:
<?php $jag = mysqli_connect($host, $user, $pass, $db); // connects to the database
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query2 .= "UPDATE inst_prod_stor SET age_type = '2' WHERE payer_mail = '$pmail' AND file_name = '$fname';";
print_r($query2);
// execute the 'update' multi query
$result2 = mysqli_multi_query($jag, $query2) or die(mysqli_error($jag));
mysqli_close($jag); ?>
I have also checked the source code on my webpage after I execute the php file that cotains this code and it is fine. I receive no errors. I actually used the 'print_r' function to check that no data was being left out before the 'mysqli_multi_query' function executed. And in fact, no data was left out. The result of the function is almost perfect every single time I execute the code. The only imperfection is the fact that one row of the table is never of updated. And each time it's a different row.
I really need help on this one, it is pretty much the last leg of a 2 or 3 week coding journey before I finish up a project that I am currently working on. Thanks!
use mysql_real_escape_string and remove . near $query2
$pmail = mysql_real_escape_string($pmail);
$fname= mysql_real_escape_string($fname);
$query2 = "UPDATE inst_prod_stor SET age_type = '2' WHERE payer_mail = '$pmail' AND file_name = '$fname';";
$result2 = mysqli_multi_query($jag, $query2) or die(mysqli_error($jag));
will only die() if the first query in $query2 has an error.
I suggest that you use a do-while loop to establish a means to debug non-first query sql failures using mysqli_error() & mysqli_affected_rows().
Strict Standards: mysqli_next_result() error with mysqli_multi_query

How to connect to 2 databases at the same time in PHP

I am trying to connect to 2 databases on the same instance of MySQL from 1 PHP script.
At the moment the only way I've figured out is to connect to both databases with a different user for each.
I am using this in a migration script where I am grabbing data from the original database and inserting it into the new one, so I am looping through large lists of results.
Connecting to 1 database and then trying to initiate a second connection with the same user just changes the current database to the new one.
Any other ideas?
You'll need to pass a boolean true as the optional fourth argument to mysql_connect(). See PHP's mysql_connect() documentation for more info.
If your database user has access to both databases and they are on the same server, you can use one connection and just specify the database you want to work with before the table name. Example:
SELECT column
FROM database.table
Depending on what you need to do, you might be able to do an INSERT INTO and save a bunch of processing time.
INSERT INTO database1.table (column)
SELECT database2.table.column
FROM database2.table
Lucas is correct. I assume that both the databases are hosted on the same host.
Alternatively, you can create only 1 db connection and keep swapping the databases as required. Here is pseudo code.
$db_conn = connect_db(host, user, pwd);
mysql_select_db('existing_db', $db_conn);
-- do selects and scrub data --
mysql_select_db('new_db', $db_conn);
-- insert the required data --
I would suggest using two connection handlers
$old = mysql_connect('old.database.com', 'user', 'pass);
mysql_select_db('old_db', $old);
$new = mysql_connect('new.database.com','user','pass);
mysql_select_db('new_db', $new)
// run select query on $old
// run matching insert query on $new
If it's an option, use PDO: you can have as many database connections open as you like.
Plus, assuming your executing the same queries over and over, you can use prepared statements.
You can easily use 2 databases in same time with following Codes:
<?php
define('HOST', "YOURHOSTNAME");
define('USER', "YOURHOSTNAME");
define('PASS', "YOURHOSTNAME");
define('DATABASE1', "NAMEOFDATABASE1");
define('DATABASE2', "NAMEOFDATABASE2");
$DATABASE1 = mysqli_connect(HOST, USER, PASS, DATABASE1);
$DATABASE2 = mysqli_connect(HOST, USER, PASS, DATABASE2);
if(!$DATABASE1){
die("DATABASE1 CONNECTION ERROR: ".mysqli_connect_error());
}
if(!$DATABASE2){
die("DATABASE2 CONNECTION ERROR: ".mysqli_connect_error());
}
$sql = "SELECT * FROM TABLE"; /* You can use your own query */
$DATABASE1_QUERY = mysqli_query($DATABASE1, $sql);
$DATABASE2_QUERY = mysqli_query($DATABASE2, $sql);
$DATABASE1_RESULT = mysqli_fetch_assoc($DATABASE1_QUERY);
$DATABASE2_RESULT = mysqli_fetch_assoc($DATABASE2_QUERY);
/* SHOW YOUR RESULT HERE WHICH DATABASE YOU WANT FROM */
echo $DATABASE1_RESULT['id'];
echo $DATABASE2_RESULT['id'];
/*After complete your all work don't forgot about close database connections*/
mysqli_close($DATABASE1);
mysqli_close($DATABASE2);
?>
First Connect Two Database
$database1 = mysql_connect("localhost","root","password");
$database2 = mysql_connect("localhost","root","password");
Now Select The Database
$database1_select = mysql_select_db("db_name_1") or die("Can't Connect To Database",$database1);
$database_select = mysql_select_db("db_name_2") or die("Can't Connect To Database",$database2);
Now if we want to run query then specify database Name at the end like,
$select = mysql_query("SELECT * FROM table_name",$database1);

Categories