Can I use DECLARE as an SQL statement in PHP - php

I am trying to execute a query in PHP, but this code wouldn't work for some reason, it doesn't detect the keywords at all(DECLARE, SELECT, WHERE). Is there anything I can do and after all can I even use DECLARE in PHP as a mySQLi statement.
$sql2 ="DECLARE #MaxID INT; SELECT #MaxID = MAX(productID) FROM products; UPDATE sunglasses SET sunglassesId = #MaxID WHERE sunglassesId = 0;";
After all I am trying to update a field in Table1 where its initial value is 0 with a value from a field in Table2.
Hope that made sense.
P.S tried this query in Microsoft SQL Management studio and it worked, in PHP it doesnt.

change your query to this and you don't need any other variable:
UPDATE sunglasses
SET sunglassesId = (SELECT MAX(productID) FROM products)
WHERE sunglassesId = 0;

Related

#variable mysql return null value on php mysql execution

I have this mysql need to run in php:
$sql_subject_summary = "SELECT
c.subject_code_id, c.subject_name, #total_target:= SUM(s.total_target_question) AS total_target_question,
#total_correct := ROUND((RAND() * (#total_target-10))+10) AS total_correct,
(#total_correct / #total_target)*100 AS percent, c.icon_filename
FROM
edu_subject_code c LEFT JOIN wkp_wg_student_subject s ON c.subject_code_id=s.subject_code_id
WHERE s.student_id=$student_id AND s.week_id = $current_week_id
$sql_inject
GROUP BY s.subject_code_id ";
However, the values of #total_correct, #total_target return null on php mysql execution .
When I run in mysql IDE, then the result is ok.
How to solve this problem?
That's right cause for that to work you need to use SELECT INTO... construct like select col1 into #arg1 from tbl1. Moreover since you are running the query from PHP why you need that at all? if you really need that then consider wrapping the query in a stored procedure and have those parameter as OUT parameter.
Well it's return null cause you are not selecting those parameter. After your query executes, you need to select those parameter saying select #total_correct, #total_target;.
Why don't you just run the query as is (like below) and fetch the specific columns value
SELECT
c.subject_code_id, c.subject_name, SUM(s.total_target_question) AS total_target_question,
ROUND((RAND() * (#total_target-10))+10) AS total_correct,
(#total_correct / #total_target)*100 AS percent, c.icon_filename
FROM
edu_subject_code c LEFT JOIN wkp_wg_student_subject s ON c.subject_code_id=s.subject_code_id
WHERE s.student_id=$student_id AND s.week_id = $current_week_id
$sql_inject
GROUP BY s.subject_code_id

PDO:Individual results from multiple SQL statements executed together

Suppose I execute the statement
$sql = "UPDATE `table1` SET v1 = 'v1' WHERE id = 'aaa';";
$sql .= "UPDATE `table2` SET v1 = 'v1' WHERE id = 'aaa';";
$code = $dbh->exec($sql);
Now here is the issue
table1 has v1 set to v0. So the first statement causes a row change. $code is > 0. GOOD
table1 has v1 already at v1. The first statement causes NO row change. table2 has v1 set to v0 so the second statement causes a row change.
However - the result being returned is still zero (for the first of the two staements).
Question -is there any way to get the result of the individual statements without executing the two statements separately?
maybe you consider using mysqli_multi_query() for your queries.

Using SQL Server, is there a way to query (555) 344-2524 using 5553442524?

Using the PHP SQLSRV driver to connect to SQL Server 2000, is there a way I could match all of these rows using this piece of data: 5553442524?
555-344-2524
(555) 344-2524
555.344.2524
1-555-344-2524
I imagine this would be done through a specific query probably using a stored procedure?
Thank you.
For SQL 2000 the only way I can think of would be using the REPLACE function.
declare #SearchTerm bigint
Set #SearchTerm = 5553442524
Select * From dbo.Table
Where Replace(Replace(Replace(Replace(Col1,'-',''), '(',''),')',''),'.','')
= #SearchTerm
The problem with this would be it wouldn't cater for the leading 1.
A better way would be wrap all this logic in to a function.
e.g.
Create Function dbo.fn_FormatTelephoneNumber(#input varchar(100))
returns bigint
as begin
declare #temp bigint
Set #temp = Replace(Replace(Replace(Replace(#input ,'-',''), '(',''),')',''),'.','')
If Len(#temp) = 11
begin
Set #temp = Right(#temp, 10)
end
return #temp
End
To call the function you would use it like so:
Select *,
dbo.fn_FormatTelephoneNumber(YourColumnName) as [FormattedTelephoneNumber]
From dbo.YourTable
Or to use it in a WHERE clause:
Select *
From dbo.YourTable
Where dbo.fn_FormatTelephoneNumber(YourColumnName) = 5553442524
Obviously the best thing here would be to clean up the data that is stored in the columns and restrict any further "bad" data from being inserted. Although in my experience that is easier said than done.

Using a SELECT Query to look up a UPDATE Query on MySQL

I'm using a SELECT query to obtain a variable using mysql_fetch_assoc. This then puts the variable into an UPDATE variable to put the returned value back into the database.
If I hard code the value, or use a traditional variable and it goes in just fine, but it doesn't work when using a value previously retrieved from the database. I've tried resetting the array variable to my own text and that works.
$arrgateRetrivalQuery = mysql_query(**Select Query**);
$arrGate = mysql_fetch_assoc($arrgateRetrivalQuery);
$arrivalGateTest = $arrGate['gatetype'];
$setGateAirportSQL = "UPDATE pilots SET currentgate = '".$arrivalGateTest."' WHERE pilotid = '".$pilotid."'";
$setGateAirportQuery = mysql_query($setGateAirportSQL);
// Close MySQL Connection
mysql_close($link);
This will just make the field to update have nothing in it, however whenever I remove the variable from the SELECT to one I define, array or not, it will work.
Hope this is clear enough. Thanks in advance.
Is arrivalGateTest a number or a string? How did you try to put another value in the query? If you are sure the previous query returns a value, try to write: $setGateAirportSQL = "UPDATE pilots SET currentgate = '$arrivalGateTest' WHERE pilotid = '$pilotid'";.
Just change your sql to inlcude a subquery.
You could use the following general syntax:
UPDATE pilots SET currentgate = (SELECT gate FROM airport WHERE flight='NZ1') WHERE pilotid='2';
which is demonstrated on this fiddle
This saves the extra query and more accurately describes what you are trying to achieve.
WARNING - test it carefully first!

UPDATE sql query and get the updated field in one single query

I'm trying to update a value of a column using the codeigniter query function like this:
$this->db->query("UPDATE table SET val = val + 1 WHERE name = 'xxxxx');
Is there any way to get the result of this update in the same query function? I have to do a select query in order to do it and it's dangerous because of the amount of users this application is managing.
If there is another query in between the update and the select, the result would not be correct.
Thanks!
Use transaction and for update. This is an example from zend, which is a similar kind of db accessing thing:
$db->beginTransaction();
$val = $db->select()->forUpdate()->from('table', 'val')->orderBy('val DESC')->limit(1)->query()->fetchColumn();
$db->update('table', 'val = '.($val+1), 'name = "xxx"');
$db->commit()
The for-update with the transaction prevents another query interfering.
Learn more about for update here: http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
and about codeigniter transactions here: http://ellislab.com/codeigniter/user-guide/database/transactions.html (thanks to #Nanne for that)

Categories