Can't add 1 to a user-variable in SQL incrementally - php

It's possibly due to the variable #count not being recognised as an integer but in my research I've come across many example similar to #count = #count + 1; That's why I'm confused as to why this breaks my code when introduced:
$setCount = "SELECT #count:=5";
$uncategorise = "UPDATE pictures
SET category = '0',
pictureorder = #count,
#count:=#count+1
WHERE category = '$categoryID'
AND username = '$username';
$queryCount = mysql_query($setCount) or die(mysql_error());
$queryUncat = mysql_query($uncategorise) or die(mysql_error());

because this is an user defined variable,
which only stand/available for the same session/connection
You can store a value in a user-defined variable in one statement and then refer to it later in another statement. This enables you to pass values from one statement to another. User-defined variables are connection-specific. That is, a user variable defined by one client cannot be seen or used by other clients. All variables for a given client connection are automatically freed when that client exits.
There is an easy solution -- php mysqli_multi_query

You could create a field in the DB that does the counting and then retrieve the data from there.

Related

For loop stopping before get to number needed

My idea is to make tooltip for new users on website. They will go through the tooltips and each time they complete a tooltip it inserts into DB.
However i've got a button which is skip all. So my idea is to insert all the reminder tooltips which they've not completed into the DB with for loop.
So it works if there has been no tooltips clicked already. So the tooltip would be equal to 1 because coming through the $data is equal to 0. However if the tooltip is equal to 1 when passed through $data it gets a +1 and the for loop doesn't seem to post anything into database
$NumberOfTooltips = 2;
(int)$data->tooltipLastID = ((int)$data->tooltipLastID === 0) ? 1 : (int)$data->tooltipLastID + 1;
for ($x = (int)$data->tooltipLastID; $x <= $NumberOfTooltips; $x++) {
$query = "";
$query = "INSERT INTO tooltips ";
$query .= "(tooltip_id, inserted) VALUES ($x, NOW())";
database::query($query);
$this->id = database::getInsertID();
}
On the broken loop the value of (int)$data->tooltipLastID is 2
Is it because the (int)$data->tooltipLastID is already equal to $NumberOfTooltips?
General improvements
These do not directly solve the question asked but they do give you a helping hand in clarifying your data and steaming out any secondary bugs and bloopers. Also pointing out some best (or at least, better) practise.
$x is a lazy and poorly defined counter. Prefer using descriptve veraibles such as $tooltipCounter
$data->tooltipLastID should not start at 1; use the same syntax as every other integer number system in PHP/programming and start at zero. If you need a one then add +1 only when it's needed (VALUES (".$x+1.")).
$NumberOfTooltips = 2; The number 2 is probably not high enough for adequate testing.
var_dump($data->tooltipLastID) and var_dump($NumberOfTooltips) to check both values are what you expect.
Rewrite the test code to take the variables out of the code so that you can check your Database connction works correctly (such as if you're trying to insert into a string field-type by mistake)
$query = ""; is redundant.
You should not need to type cast (int) your object variables ($data->whatever) all the time but type cast them when they're set.
Also by adding +1 to a variable PHP automatically recasts the variable as an int anyway.
Check that your $data->tooltipLastID is publicly accessible/writable.
You use $this ; so which class are you in? Are you self referencing the data class?
A bank holiday is just one day.
It is better the inserted Database column is set by the database automatically upon insert. You can use this SQL to alter your current table:
ALTER TABLE <yourTable> MODIFY COLUMN inserted timestamp DEFAULT CURRENT_TIMESTAMP
Check the type of $data->tooltipLastID? And plz use var_dump($data->tooltipLastID) and var_dump((int)$data->tooltipLastID) before the for loop to see what indeed the original value and the $x is.
Strange type casts will result in strange bugs...

save MySQL rows in an array and save it in session variable

I want to get rows from MySQL Database and save two specific values(row[0] & row[6]) in $_SESSION variable for comparison later on.
The code looks like below:
$sqlResult =mysql_query("SELECT * FROM questionbank WHERE quizName ='$quizNames' ORDER BY RAND() limit 6")
while ($row= mysql_fetch_array($sqlResult))
{
$questionPkId = $row[0];
echo $_SESSION['$questionPkId'] = $row[6];
}
The Problem is I can't get this values in other pages. Can I make an associative array with session variable (though i tried array_push(), But it did not work).
A couple issues with your code. First up, make sure you call session_start on any page that uses sessions. Without it, you will not be able to access the variables previously set.
Second up, when a variable is called inside single quotes it is taken literally, meaning your session define statement is always assigning the variable to same thing, and hence overwriting what it should be.
$_SESSION[$questionPkId] = $row[6];
And that will assign the value to the actual value of $questionPkId. Aside from those issues, your session items should work, and if they are not you will need to provide us with more of your code.
Try without single quotes:
$_SESSION[$questionPkId] = $row[6];

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!

MySQL custom global defined variable

In my database design, I tend to store some variable that is meant to be acting as a ROLE or TYPE as SMALLINT.
For example:
CREATE TABLE `house` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` smallint(11) NOT NULL,
And in PHP, I do:
define('HOUSE_SMALL_TYPE', '0');
define('HOUSE_MEDIUM_TYPE', '1');
So in PHP, in SELECT queries I do:
$this->db->query("SELECT * FROM house
WHERE type = ?;", HOUSE_SMALL_TYPE);
My questions are:
In the PHP part, is there is a better way to do this?
In the MySQL itself, does MySQL also has global define functionality (like the define in PHP)?
I also want to do kind of
SELECT * FROM house WHERE type = HOUSE_SMALL_TYPE;
in MySQL query.
My purpose is that when I do SELECT in MySQL, no way I'm going to keep mapping the value 0,1,2 with its real meaning. Just convenience for viewing the tables values, without changing the structure table and fields.
Since MySQL 5.5 it's not possible to set a global user-defined variable.
A work-around might be to create a stored procedure that would return what you need.
DROP PROCEDURE IF EXISTS HOUSE_SMALL_TYPE;
DELIMITER //
CREATE PROCEDURE HOUSE_SMALL_TYPE ()
BEGIN
SELECT 0;
END//
DELIMITER ;
and then call it.
CALL HOUSE_SMALL_TYPE();
The DROP statement is required in order to be able to modify it.
IMHO, MySQL has a huge gap in this area, apparently in the latter versions. One alternative might have been to resort to setting OS environment variables, but how such values can be retrieved from within MySQL, I've been unable to see.
There's a whole page here: https://dev.mysql.com/doc/refman/5.0/en/setting-environment-variables.html teaching us how to "set" OS environment variables in the shell, but not a word on actually calling such variables in MySQL.
As another workaround, using a FUNCTION might be considered more lightweight than a STORED PROCEDURE, like so:
CREATE DEFINER=`root`#`localhost` FUNCTION `DEFAULT_COUNTRY_CODE`() RETURNS CHAR(4)
DETERMINISTIC
RETURN '+234';
Elsewhere in your query, you can then do:
SELECT CONCAT(DEFAULT_COUNTRY_CODE(), "-", telephone) FROM contacts WHERE CountryCode = "NGA"
Your approach is fine, if you want to see the values in MySQL instead of 1, 2, 3 etc. then consider this:
define('HOUSE_SMALL_TYPE', 'HOUSE_SMALL_TYPE');
define('HOUSE_MEDIUM_TYPE', 'HOUSE_MEDIUM_TYPE');
Then in MySQL you can use:
SELECT * FROM house WHERE type = 'HOUSE_SMALL_TYPE';
You just need to remember that you cannot just jam any value you like into house.type without having support for it in PHP.
Even better consider this:
class HouseType {
const SMALL = 'SMALL';
const MEDIUM = 'MEDIUM';
}
or
class House {
const TYPE_SMALL = 'SMALL';
const TYPE_MEDIUM = 'MEDIUM';
}
because then you can use HouseType::SMALL or House::TYPE_SMALL in your PHP code rather than using a global define. By doing this you may benefit from code completion in some IDE's.
Since MySQL 5.5 it's not possible to set a global user-defined variable, another workaround could be helping table like
create table glob_var(key varchar(10) unique not null, val varchar(10) not null);
I suggest using MySQL variables:
SET HOUSE_SMALL_TYPE = 0;
SET HOUSE_MEDIUM_TYPE = 1;
Then, in your queries you may use these variables:
SELECT * FROM house WHERE type = #HOUSE_SMALL_TYPE;
This method defines session variables:
If you change a session system variable, the value remains in effect
until your session ends or until you change the variable to a
different value. The change is not visible to other clients.
If you want to define global MySQL variables (available to all sessions):
SET GLOBAL HOUSE_SMALL_TYPE = 0;
SET GLOBAL HOUSE_MEDIUM_TYPE = 1;
To indicate explicitly that a variable is a global variable, precede
its name by GLOBAL or ##global.. The SUPER privilege is required to
set global variables.
Documentation:
SET statement
Using system variables
User-defined variables

SQL Query Not Reading Variables

My query below updates a record using variables to identify the data in the DB. I think my syntax is correct although it might be wrong. Also, I am absolutely sure that the variables have legitimate values in them. Why won't this query work?
UPDATE `databasename`.`".$tablename."` SET `stock` = '".$f."' WHERE `myerspark`.`item_id` ='".$g."' LIMIT 1
Thanks guys. Tom, yes I have tried that and it works fine. But it is frustrating because I echo all three variables at the end of the script and they all display legitimate values.
Hamish, how do I view these errors?
Jon_Darkstar, these variables are assigned in previous lines of code. Here is my entire code block:
//variables $f, $g, and $tablename assigned from POST variables in previous lines
mysql_select_db($database_Yoforia, $Yoforia);
mysql_query("UPDATE `yoforiainventory`.`".$tablename."` SET `stock` = '".$f."' WHERE `".$tablename."`.`item_id` ='".$g."' LIMIT 1 ");
mysql_close($Yoforia);
echo ($f);
echo ($tablename);
echo ($g);
Again, when i echo these variables, they all come out with good values.
I'm kind of confused what belongs to SQL, what belongs to PHP, where that string comes from, etc. What you have might be fine (if there is a double quote in front and end that i dont see.
I'd probably write it like this:
$sql = "UPDATE databasename.$tablename SET stock = '$f' WHERE myerspark.item_id = '$g' LIMIT 1"
$res = mysql_query($sql, $conn).....
you can backtick more stuff (and/or do mysql_real_escape) for 'extra safety;, but that covers the idea.
What is myerspark? i dont see how it relates to the query, that is probably you're real meaningful error, whether there is a syntax error or not. If myerspark is a seperate table from tablename then you've got an issue here, maybe a JOIN you ought to have?

Categories