Random number insert mySQL not working - php

Hey all i am created 2 random numbers like so:
$firstlink = intval(mt_rand(100, 999) . mt_rand(100, 999) . mt_rand(1, 9) . mt_rand(100, 999)); // 10 digit
$secondLink = intval(mt_rand(1000, 999) . mt_rand(1, 999) . mt_rand(10, 99) . mt_rand(100, 999));
And this is my insert code:
$result = mysql_query("INSERT INTO userAccount
(Category,Fname,LName,firstlink,secondLink,AccDate)
VALUES ( '" . $cat . "',
'" . $fname . "',
'" . $lname . "',
" . $firstlink . ",
" . $secondLink . ",
'" . date('Y-m-d g:i:s',time()). "');");
It has no errrs and it places the data into the mysql database. However, its always the same number for BOTH firstlink and secondLink no matter who i add to the database and i have no idea why its doing it!
The datatype for both rows is INT(15)

Remove intval and all will work fine.
$firstlink = mt_rand(100, 999) . mt_rand(100, 999) . mt_rand(1, 9) . mt_rand(100, 999); // 10 digit
32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. With intval you got 2147483647 mostly.

You can simplify your code and improve the randomness of the code like this:
$firstlink = mt_rand(10000,99999) . mt_rand(10000,99999);
$secondLink = mt_rand(10000,99999) . mt_rand(10000,99999);
echo "INSERT INTO userAccount
(Category,Fname,LName,firstlink,secondLink,AccDate)
VALUES ( '" . $cat . "',
'" . $fname . "',
'" . $lname . "',
" . $firstlink . ",
" . $secondLink . ",
'" . date('Y-m-d g:i:s',time()). "');"
PHPFiddle: http://phpfiddle.org/main/code/6nf-wpk
This will build your random 10-digit code by making two random 5 digit codes and joining them together. Is is simpler and easier to follow with less parts making it up. It had to be done with two mt_rand()s because the maximum number possible is 2147483647. For each mt_rand() function you're using, you're preventing a 0 from being the first digit in that section of the number, because you're starting the first digit at between 1 and 9.
If you don't care about the first number being only a 1 or 2 (and never being 3-9 or 0) you can simply use
$firstlink = mt_rand(1000000000,2147483647); // random 10 digit number
$secondLink = mt_rand(1000000000,2147483647); // random 10 digit number
As general coding tips:
Be consistent with how you name variables. You have a lowercase "L" in "$firstlink" and a capital "L" in "$secondLink". PHP is case-sensitive and you'll end up using the wrong name and getting unexpected (blank) results elsewhere in your program.
Be be careful never to put any user-provided data into a SQL command without protecting against SQL Injection attacks. Use parameterized queries as a rule. See How can I prevent SQL injection in PHP? for more details and examples.

Related

Showing a limited number of mysqli_fetch_assoc array

I want to create an array with the help of MYSQL and display it the following way:
while ($array = mysqli_fetch_assoc($res))
{
echo $array["first_name"] . ", "
. $array["last_name"] . ", "
. $array["personal_id"] . ", "
. $array["salary"] . ", "
. $array["birthday"] . "<br />";
}
To improve usability, I only want to display 10 results, put a link to the next 10 results at the bottom and display these on another page.
How do I have to change the while-condition in order to only display the first 10 results of my result?
I tried searching for a solution but I couldn't find anything that fits my needs, so any help is appreciated!
Thanks in advance!
Check offset and limit conditions in mysql.
Example: to show 16 - 26 records from result query.
$sql = "SELECT * FROM Table LIMIT 10 OFFSET 15"
If what you want is just a way to break out of the loop after the first 10 results.
$counter = 1;
while (($array = mysqli_fetch_assoc($res)) || ($counter < 10))
{
echo $array["first_name"] . ", "
. $array["last_name"] . ", "
. $array["personal_id"] . ", "
. $array["salary"] . ", "
. $array["birthday"] . "<br />";
$counter++;
}

PHP: creating a for loop with dynamic Variables

I'm trying to slim down the code:
I want to make a for loop out of this part, but it wouldn't work.
$line1 = $frage1[0] . '|' . $frage1[1] . '|' . $frage1[2] . '|' . $frage1[3];
$line2 = $frage2[0] . '|' . $frage2[1] . '|' . $frage2[2] . '|' . $frage2[3];
$line3 = $frage3[0] . '|' . $frage3[1] . '|' . $frage3[2] . '|' . $frage3[3];
$line4 = $frage4[0] . '|' . $frage4[1] . '|' . $frage4[2] . '|' . $frage4[3];
$line5 = $frage5[0] . '|' . $frage5[1] . '|' . $frage5[2] . '|' . $frage5[3];
This is my attempt:
for ($i=1; $i<6; $i++){
${line.$i} = ${frage.$i}[0] . '|' . ${frage.$i}[1] . '|' . ${frage.$i}[2] . '|' . ${frage.$i}[3];
}
EDIT:
This is the solution that works (just so simple :-p):
for ($i=1; $i<18; $i++){
${"line".$i} = implode("|", ${"frage".$i});
fwrite($antworten, ${"line".$i});
}
for ($i=1; $i<6; $i++){
$line[$i] = $frage[0] . '|' . $frage[1] . '|' . $frage$i[2] . '|' . $frage$i[3];
}
This will insert the same thing you posted abov e in line 1 to 6. Is this what you are looking for?!
for ($i=1; $i<6; $i++){
${"line$i"} = ${"frage$i"}[0] . '|' . ${"frage$i"}[1] . '|' . ${"frage$i"}[2] . '|' . ${"frage$i"}[3];
}
That works too!
TL;DR
You might find the documentation on variable variables useful but it looks like the problem is that PHP cannot handle the unquoted string inside your curly brackets.
So instead of ${frage.$i} you need ${"frage$i"}.
Another Approach
However, this is probably not the clearest way to solve this problem. It certainly gives me a bit of a headache trying to work out what this code is trying to do. Instead I would recommend adding all of your $frage to an array first and then looping as follows:
$lines = array();
$frages = array($frage1, $frage2, $frage3, $frage4, $frage5)
foreach($frages as $frage) {
$lines[] = join('|', $frage);
}
Note in particular that you can use join to concatenate each $frage with a | inbetween each, rather than doing this concatenation manually. You could always use [array_slice][2] if you really did only want the first 4 elements of the array to be joined.
If you have a significant number of $frage variables and don't want to add them to an array manually then:
$frages = array();
for($i = 1; $i < x; $i++) {
$frages[] = ${"frage$i"}
}
If you really need each $line variable rather than an array of lines, then you can use extract although this will give you variables like $line_1 rather than $line1:
extract($lines, EXTR_PREFIX_ALL, "line")
However, I would recommend taking a serious look at why you have these numbered $frage being generated and why you need these numbered $line as your output. I would be very surprised if your code could not be re-factored to just use arrays instead, which would make your code much simpler, less surprising and easier to maintain.

Update multiple rows/columns in php/mysql

I have the following line:
$reset = "UPDATE pidgeon SET obt='" . $hour . "' WHERE tag='" . $tag . "'";
Which updates just fine. However I need to update an additional row (kill) and I keep getting syntax errors. I've tried the following:
$reset = "UPDATE pidgeon SET obt='" . $hour . "', kill='1' WHERE tag='" . $tag . "'";
$reset = "UPDATE pidgeon SET kill='1', obt='" . $hour . "' WHERE tag='" . $tag . "'";
$reset = "UPDATE pidgeon SET obt='" . $hour . "', kill='" . $num . "' WHERE tag='" . $tag . "'";
I've even done 2 separate UPDATE queries and I get the same syntax error message. I've narrowed it down to the system having issue with the kill row but I'm not sure what's the issue. I've tried setting kill as INT, SMALLINT, BOOL, even CHAR and trying to use 't/f' as values for it. I still get a syntax error. Any suggestions?
KILL is a reserved keyword, so you'll have to enclose it in backticks, like so:
$reset = sprintf("UPDATE pidgeon SET `kill`='1', obt='%s'
WHERE tag='%s'", $hour, $tag);
Kill is actually a syntax, you can't use them directly.
Just replace kill with another name.

Generating E-pin or random Unique Number in PHP MYsql

I was searching for a php script which could generate a unique 10 digit number (numerical) for my project.
I know very little about Php and here is my code, please help.
Code here is to generate a Random pin and store in database table lucky_coupon_pins.
//check for generate button
if (isset($_POST['generate_pin'])) {
//generate a random number
$random_number=mt_rand();
//once the code is generated check if it exists in table , if so generate again else move on
$row_count = $db->row_count("SELECT * FROM " . config_item('cart', 'table_lucky_coupon_pins') . " WHERE lucky_pin = '" . $random_number . "'");
if($row_count>0)
{
$random_number=mt_rand();
$row_count = $db->row_count("SELECT * FROM " . config_item('cart', 'table_lucky_coupon_pins') . " WHERE lucky_pin = '" . $random_number . "'");
}
//insert to database
$values = array(
'lucky_pin' => $random_number,
'lucky_pin_value' => $_POST['lucky_pin_value']
);
$db->insert(config_item('cart', 'table_lucky_coupon_pins'), $values);
Here I am checking the generated pin for once, if it already exists another pin is generated..I do not know how far is this unique, also the generated pin is sometimes 9 digit and sometimes its 10 digit.
As stated in the manual mt_rand() takes two parameters, a min and a max value, so to get a 10 digit random value, use either:
$random_number = mt_rand(1000000000, 9999999999);
or
$random_number = mt_rand(1,9);
for ($i = 0; $i < 9; $i++) {
$random_number .= mt_rand(0,9)
}
Is it unique? As it is, it is with high probability, but not for sure. (You only check once if it already exists.) You might consider using a loop e.g.
$row_count = 1;
while ($row_count > 0) {
$random_number = mt_rand(1000000000, 9999999999); // i prefer the other option but this one is somehow shorter
$row_count = $db->row_count("SELECT * FROM " . config_item('cart', 'table_lucky_coupon_pins') . " WHERE lucky_pin = '" . $random_number . "'");
}
mt_rand() is supposed to be pretty good (or the best way to return random number using native php function), so have some faith in it. Also if you want 10 digit number only, try:
$random_number = mt_rand(1000000000, 9999999999);
Here is a simple function for generating pin codes
function GeneratePinCode($chars){
$pin="";
while ($chars!=0){
$pin .=rand(0,9);
$chars--;
}
return $pin;
}
As for the uniqueness of the pin code, you can store each pin that you generate in the database and run a check each time you generate a new one.

How to round mysql column in a table output

I need to round a result of a SQL round in a table array output. I can't figure out the syntax...
$result = mysql_query("SELECT `Energ_Kcal`*`yield`*`qty` AS `cal` FROM allinnot a
WHERE `own_id` = $user->id");
echo "<tr><td>" . $row['Shrt_Desc'] . "</td><td> " . $row['desc'] . "</td><td>" . $row['cal'] . " cal</td></tr>";
cal returns a value with many numerals beyond the decimal. I just need it to show a whole rounded integer. I tried ROUND(), but I must be putting it in the wrong place.
general syntax
ROUND( expression, 2 )
The ROUND should go around the values, try this:
$result = mysql_query("SELECT ROUND(`Energ_Kcal`*`yield`*`qty`,2) AS `cal` FROM allinnot a
WHERE `own_id` = $user->id");
echo "<tr><td>" . $row['Shrt_Desc'] . "</td><td> " . $row['desc'] . "</td><td>" . $row['cal'] . " cal</td></tr>";
You could also check out PHP's round() or, possibly from your description int_val().

Categories