In my PHP file, I use this line to pull data from my mySQL database:
$query = "SET #rank=0; SELECT #rank:=#rank +1 as rank, Blah Blah...";
If I check the SELECT statement in phpMyAdmin's SQL window (without $query= ) it works fine.
But, if I use it in PHP, then I get an error. It doesn't like the "SET #rank=0;" bit. Is there a way to use "SET #rank=0;" when it's in "$query=" ? Is there a workaround?
The rest of the code is standard stuff for pulling data from a db:
public function getmyData() {
$mysql = mysql_connect(connection stuff);
$query = "SELECT #rank:=#rank +1 as rank, formatted_school_name, blah blah";
$result = mysql_query($query);
$ret = array();
while ($row = mysql_fetch_object($result)) {
$tmp = new VOmyData1();
$tmp->stuff1 = $row-> stuff1;
$tmp->stuff2 = $row->stuff2;
$ret[] = $tmp;
}
mysql_free_result($result);
return $ret;
}
Update: I'm trying to use Amerb's suggestion of using multi-query. I concatenated the query like so:
$query = "SET #rank = 0";
$query .= "SELECT #rank:=#rank +1 as rank...
I changed the result to:
$result = $mysqli_multi_query($query);
But, it's failing for some reason. I'm on a machine running PHP 5.2. Any suggestions?
This guy here seems to have a way of setting the variable in the same query to zero. I don't have MySQL set on up on this machine to try it, though.
Here's the query he suggests in his blog post:
select #rownum:=#rownum+1 ‘rank’, p.* from player p, (SELECT #rownum:=0) r order by score desc limit 10;
(Is there some homework assignment coming due somewhere having to do with computing ranks? This is the third question I've seen on this in two days.)
Are you checking for duplicate scores?
Try executing it as 2 separate successive queries.
You have to enable the use of multiple queries in one, but i forgot how do do this at the moment. It's a security feature.
Use mysql_multi_query() or rather mysqli_multi_query() instead of mysql_query()
Related
$sql2 ="UPDATE table1,table2 SET table2.password2 = ".password_hash(."table1.password1".,PASSWORD_DEFAULT)." WHERE table1.username = table2.username";
I am trying to use Php functions in Mysql update queries instead of iteration, but it doesn't seem to work. Please let me know if there is anyway I can achieve this without iteration, if with Stored procedures I can, please give a small example as I have never made a stored procedure before, thanks in advance
The below code is working good for you :) .
$sql2 ="UPDATE table1,table2 SET table2.password2 = '".password_hash("table1.password1",PASSWORD_DEFAULT) ."' WHERE table1.username = table2.username";
Try With This Below Query:
"UPDATE table2 SET table2.password2 = (SELECT '".password_hash("table1.password1",PASSWORD_DEFAULT) ."'from table1 WHERE table1.username = table2.username)"
You are missing single quote, You can try like this
$pass = password_hash("table1.password1",PASSWORD_DEFAULT);
$sql2 ="UPDATE table1,table2 SET table2.password2 = '$pass' WHERE table1.username = table2.username";
I've the following code:
$query = "UPDATE `'._DB_PREFIX_.'specific_price` sp SET sp.`from`=NOW(), sp.`to`=DATE_ADD(NOW(), INTERVAL 19 HOUR)
INNER JOIN `'._DB_PREFIX_.'product` p ON (sp.id_product = p.id_product)
WHERE p.`id_manufacturer` = '.(int)$id_manufacturer";
//Run the Query
$result = mysql_query($query);
?>
I know I have to modify the location and usage of _DB_PREFIX And $id_manufacturer but where and how?
I admit that I'm quite lost right now and some help would be highly appreciated.
Thank you in advance
// define variable for database prefix
// you can also use simple php variable here instead of using constant
define(_DB_PREFIX_, "database-name");
// filter data
$id_manufacturer = (int)$id_manufacturer;
// prepare query
$query = "UPDATE "._DB_PREFIX_."specific_price sp
SET sp.`from`=NOW(), sp.`to`=DATE_ADD(NOW(), INTERVAL 19 HOUR)
INNER JOIN "._DB_PREFIX_."product p USING id_product
WHERE p.id_manufacturer = $id_manufacturer";
//Run the Query
$result = mysql_query($query);
Note: Do NOT use above mentioned code in any production system. Please consider this just as tutorial. Its very high time to start using PDO or mysqli. You can google it and get more information about it.
The solution to this problem might be a simple over sight of mine.
I am trying to run a MYSQL query stored as a string in PHP. The query runs fine using DBM tool like Navicat but returns false in my PHP development enviorment. Is there something I've over looked?
SET #running_sum = 0;
SELECT
TID,
SumTotal,
T.`Freight`,
T.`Insurance`,
T.`Discount`,
CONCAT(
'$',
FORMAT(
#running_sum :=#running_sum + SumTotal + T.`Freight` + T.`Insurance` - T.`Discount`,
2
)
) AS 'Running Total'
FROM
(
SELECT
TID,
SUM(Quantity * UnitNetValue) AS SumTotal,
T.`Freight`,
T.`Insurance`,
T.`Discount`
FROM
Transactions T
JOIN `Transactions_Products` P ON T.TransactionID = P.TID
WHERE
(
T.TemplateName = ''
OR T.TemplateName IS NULL
)
AND T. STATUS = 1
GROUP BY
TransactionID
) AS T;
I am executing the query like this;
$result = mysql_query($this->query);
$this->query is a string which holds the above query, as it is displayed to you above.
The problem is mysql_query() doesn't support multiple queries. Your SET #running_sum = 0; is considered a separate query and so you'll have to execute that first:
$result1 = mysql_query("SET #running_sum = 0;");
$result2 = mysql_query($this->query); // <-- without the SET ... query
From the Manual:
mysql_query() sends a unique query (multiple queries are not supported)
Side note: The mysql_* library is deprecated, it is recommended to upgrade to a modern MySQL library such as PDO or MySQLi.
There is also possible to use multi_query method instead of query of MySQLi:
$query = "SET #running_sum = 0; SELECT ...";
$db_link->multi_query($query);
put variable like this. i guess it should work.
mysql_query("SELECT #i:=0");
mysql_query("UPDATE table_name SET id = #i:=#i+1");
I have small PHP script which has
$query = "SELECT MAX(id) FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row[0];
Which runs fine, but I want to understand why i can't access the row with the fieldname, like if i have this
$query = "SELECT id FROM `dbs`";
i am able to use the folowing
$val = $row['id'];
but whenever i use this MAX() function, i have to change to
$val = $row[0];
to access the values
I have no clue about this. Any help would be appreciated. Thankss
You need to give it an alias:
<?php
$query = "SELECT MAX(id) AS `id` FROM `dbs`";
//query run
$row = mysql_fetch_array($result);
$val = $row['id'];
Edit:
To explain this it's probably best to show an example of a different query:
SELECT MAX(`id`) AS `maxId`, `id` FROM `dbs`
Using the above it will return as many rows are in the table, with 2 columns - id and maxId (although maxId will be the same in each row due to the nature of the function).
Without giving it an alias MYSQL doesn't know what to call it, so it won't have an associative name given to it when you return the results.
Hope that helps to explain it.
SELECT MAX(id) AS myFieldNameForMaxValue
FROM `dbs`
and then
$row = mysql_fetch_array($result);
$val = $row['myFieldNameForMaxValue'];
If you run this query on mysql commandline you'll see that the field name returned by mysql is MAX(id). Try running on phpmyadmin and you'll see the same. So if you try $row['MAX(id)'] it'll work. When using a mysql function, it gets added to the name, so use an alias, like other said here, and you're good to go: SELECT MAX(id) AS id FROM dbs. Also, never forget to use the ` chars, just in case you have some columns/tables with reserved names, likefrom`.
// make empty array
$sqlArray=array();
$jsonArray=array();
// START NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// first 20 vistors
$query = "SELECT user_id FROM vistors LIMIT 20";
$result = mysql_query ($query) or die ($query);
// make vistors user query array
while ($vstr_line = mysql_fetch_array($result)){
array_push($sqlArray, $vstr_line['user_id']);
}
// implode vistors user array
$sqlArray_impl = implode("', '", $sqlArray);
// END NEED FAST WORKING ALTERNATİVES -----------------------------------------------------
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN ('$sqlArray_impl')";
$qry_result = mysql_query($query) or die($query);
while ($usr_line = mysql_fetch_array($qry_result)){
array_push($jsonArray, $usr_line['id'].' - '.$usr_line['username'].' - '.$usr_line['picture']);
}
print_r($sqlArray);
echo '<br><br>';
print_r($jsonArray);
see this my functions..
i need a replacement for fast working alternatives..
function within the range specified above, to me, running faster than the alternative.
the query will return back array ?
thx for all helpers !
Can you use a JOIN or SUB SELECT to reduce the query count from 2 to 1? Might not give much of a boost but worth a shot and a cleaner implementation.
Where is the bottleneck? Most likely the db and not the php code.
Are the tables/columns properly indexed? Run EXPLAIN on both queries.
Easiest would be to include first query as subquery eliminating one turn to the DB and a lot of code:
// Get vistors information
$query = "SELECT id, username, picture FROM users WHERE id IN (SELECT user_id FROM vistors LIMIT 20)";
$qry_result = mysql_query($query) or die($query);
Unless there is more reason to have the first one seperate, but that is not visible in your code example.
If you use PDO (recommended anyway...), you can return the result array all at once using fetchAll().
For your second query, you can use string concatenation in MySQL to directly return the result you want.