Using php functions in mysql update queries - php

$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";

Related

Where to put the _DB_Prefix_ and the $id_manufacturer?

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.

How to add a sequencial number to my insert query in mysql/php ps. not auto increment

I would like to insert a sequencial item number when everytime the user creates an exam.
everytime he creates an exam it restarts to 1. I extremely need your help, people. More power. :)
here is my code:
$examid = $_SESSION['examid'];
$itemnum = 1;
$sql = mysql_query("INSERT INTO exam_questions (question_description, question_type, question_exam_id) VALUES ('$question', '$type', '$examid')")or die(mysql_error());
$lastinsertid = mysql_insert_id();
mysql_query("UPDATE exam_questions SET question_set_id='<??????????>' WHERE question_id='$lastinsertid' LIMIT 1")or die(mysql_error());
Try doing this with a join:
UPDATE exam_questions eq cross join
(select max(question_set_id) as qsi
from exam_questions
where question_id='$lastinsertid'
) as const
SET eq.question_set_id = const.qsi + 1
WHERE question_id='$lastinsertid';
You could try something like this:
SELECT COUNT(`id`) INTO #tmpvar FROM `exam_questions` WHERE `question_exam_id`='$examid';
INSERT INTO `exam_questions`
(`question_description`,`question_type`,`question_exam_id`,`question_id`)
VALUES ('$question','$type','$examid',#tmpvar+1);
Note that those will have to be sent as separate mysql_query calls, but it should work nicely. I'm also assuming that you've correctly escaped your parameters.

Can't access row with 'fieldName' using MAX() in PHP MYSQL

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`.

PHP & MySQL: How can I use "SET #rank=0;" in $query=

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()

PHP/SQL SELECT statement using asterisk

I am having trouble getting an sql request to work. Without giving more details than needed,
$db_query = mysql_query(" select years,avg,best,win,top10,champs from `profile` where PLAYERID = '$monkey_id'");
works fine. However,
$db_query = mysql_query(" select * from `profile` where PLAYERID = '$monkey_id'");
doesn't return any results. The only change is that I'm trying to pull all fields instead of just those few. I'm at a loss to explain this. I taught myself all this stuff, so it's always possible I'm doing something dumb.
Edit:
Here's the rest of the surrounding code:
$db_query_inside = mysql_query(" select * from `profile` where PLAYERID = $monkey_id");
$db_query = mysql_fetch_array($db_query_inside);
$years_prev = $db_query['years'];
$avg_prev = $db_query['avg'];
$best_prev = $db_query['best'];
$win_prev = $db_query['win'];
$top10_prev = $db_query['top10'];
$champs_prev = $db_query['champs'];
Edit again:
Still don't know why it wouldn't work with *, but I just got what I needed done by listing the specific fields. It doesn't end up with any sort of error that can be gleaned from
die(mysql_error())
so I'm just giving up and working on stuff that reacts rationally.
Why not try:
$db_query = mysql_query(" select `profile` where PLAYERID = '$monkey_id'");
Let's do this, modify the following line to reflect below. See what the error says, if any. I tried it myself (your code) and it seems to work fine.
$db_query_inside = mysql_query(" select * from `profile` where PLAYERID = $monkey_id") or die(mysql_error());

Categories