This question already has answers here:
PHP - How get random element in array?
(6 answers)
Selecting a random element from a PHP associative array
(4 answers)
How to get random value out of an array?
(21 answers)
Closed last year.
I would like to insert a random value from a php array into a mysql table.
My php array is $profile_outM = (3,6,7)
The following command works nicely and sets user_profile to 7 for all users having user_UFR equal to 2:
UPDATE `users` SET `user_profile` = '$profile_outM[3]' WHERE `user_UFR`= 2
But how can I select a random value from $profile_outM ?
Best,
HERE is the solution (might not be very elegant / efficient) but it works:
Starting with $profile_outM as a string
I convert to an array and get the number of element
profile2array = explode(",", $profile_outM);
$length_profile2array = count($profile2array);
Then
"SET #myValues = '$profile_outM'"
"UPDATE `users` SET `user_profile` = SUBSTRING_INDEX(REVERSE(SUBSTRING_INDEX(#Values, ',', FLOOR(1+RAND()*$length_profile2array))),',',1) WHERE `user_UFR`=2"
This way, all users get a different value.
W
You can use array_rand() as #Victorbzh mentioned, or you can use:
$val = $array[mt_rand(0, count($array) - 1];
The above generates a random number using mt_rand($min, $max) ($max is inclusive). Array indexes start from 0, and count() gets the number of elements in the array.
Security Note 1: array_rand() and mt_rand() do not generate cryptographically secure values. If you want cryptographically secure values, use random_int()
Security Note 2: UPDATE `users` SET `user_profile` = '$profile_outM[3]' WHERE `user_UFR`= 2: It seems you are not using prepared statements. Make sure to use prepared statements when you are using input from the user.
Related
This question already has answers here:
getting the value of the single field output using the codeigniter active record
(5 answers)
Closed 2 years ago.
hi want to get only one column from one result from my database. So i do it in this way
$this->db->select('myclolumn')->where('id',$id);
$query = $this->db->get('mytable');
$temp=$query->row_array();
$finalresult=$temp['mycolumn'];
Maybe there is a easier or faster way to do the same?
so based on DanishAli's comment
$this->db->select('myclolumn')->where('id',$id);
$query = $this->db->get('mytable');
$finalresult=$query->row()->mycloumn;
You can do it like this:
$finalresult = $this->db->select('myclolumn')
->where('id',$id)
->get('mytable')->row()
->mycolumn;
All in only one command instead of a lot of variables and extra code.
In case you need to provide a default value if the row is null, break the command to:
$row = $this->db->select('myclolumn')
->where('id',$id)
->get('mytable')
->row();
$finalresult = ($row)?$row->mycolumn:'your default value';
This question already has answers here:
Opposite of MySQL FIND_IN_SET
(6 answers)
MySQL, PHP: Select * from table where id is not in array
(3 answers)
Select all field where field value not in array
(3 answers)
Closed 3 years ago.
I am writing an SQL query. I have an array of unknown length and I want to select the data fromMySQL by using that array in the WHERE clause of the query. This is my query right now and it is working fine
$sql = "SELECT DISTINCT messagesutou.SenderID from messagesutou where (messagesutou.SenderID !='$items[1]' AND messagesutou.SenderID !='$items[0]' AND messagesutou.SenderID !='$items[2]') AND messagesutou.RecieverID='$uid'";
But in this I know the length of array ( 3) and I just used the array name with index for testing purpose. Now i want to know if array length is unknown then how would I write this query?
$list = implode(',', $items);
and
SELECT DISTINCT SenderID
FROM messagesutou
WHERE 0 = FIND_IN_SET(SenderID, '$list')
AND RecieverID='$uid'
or (taken from Jens's answer which was deleted by him)
SELECT DISTINCT SenderID
FROM messagesutou
WHERE SenderID NOT IN ($list)
AND RecieverID='$uid'
The difference - both variants are applicable when SenderID and $items values have a numeric type, only the former when they have string type, none when they have string type and contain commas or ticks.
But the latter may be adapted:
$list = '\''.implode('\',\'', $items).'\'';
and
SELECT DISTINCT SenderID
FROM messagesutou
WHERE SenderID NOT IN ($list)
AND RecieverID='$uid'
It now acccepts any datatype and allows commas (but not ticks - they must be quoted before imploding).
This question already has answers here:
Accessing random rows from database without repetition
(2 answers)
Closed 4 years ago.
from the past few days i have had this problem with a quiz scenario in created as part of my project. i wanted random questions to be asked but when i use the rand() function , the questions are being repeated. also i figured out that since its being done on the same page and every time the page refreshes, the random number is again selected thereby leading to this flaw! so i considered storing the value of the last random que_id in a session and generating a query like so:
enter code here <?php session_start();$jsqla=mysql_query("select que_id from mst_que");$jfeta=mysql_fetch_assoc($jsqla);session_start();$id=array($jfeta['id$_SESSION['id'][] = $id;$rs=mysql_query("SELECT * FROM `mst_que` WHERE que_id NOTIN ('id') ORDER BY RAND() ")
Please help me in this. I just want to create a session array where i want to store the previously generated random number and use it in query so that it is not repeated again. please
Store it in a variable and unset it from the array of questions:
function get_question($questions)
{
$question = rand($questions);
$questionKey = array_search($question, $questions);
unset($questions[$questionKey]);
return $question;
}
Try creating an array and then assign it to any session variable, for example:
$quizQuestions[] = $questionId;
$_SESSION['question'] = $quizQuestions;
In case you want to update the value, simply fetch it and assign new value and update it in the same variable again:
$quizQuestions = $_SESSION['question'];
$quizQuestions[] = $questionId;
$_SESSION['question'] = $quizQuestions;
Make sure that you have a session started first, add the following code to the very start of this script:
if(!isset($_SESSION)) {
session_start();
}
This question already has answers here:
Split a comma-delimited string into an array?
(8 answers)
Closed 10 months ago.
I'm using laravel 5.3 and trying to build a query with multiple where and wherein function. Here is my code:
$posts_id = "1,3,4"; //from my query
$results = Post::select('*');
$results->whereIn('posts_id', [$posts_id]);
$resutls->get();
There is 1 post which have an id of 4 in my database, but my query doesn't returning anything. Though there is 4 in my post ids $posts_id = "1,3,4";.
Need help, to get posts from any of the id, which I've included in my $posts_id variable.
Thanks in Advance!
You need to pass an array to whereIn() method:
$results = Post::whereIn('posts_id', explode(',' $posts_id))->get();
Note that you don't need to call each method in a separate line. You can chain them. Also, the select('*') is not required.
You can create your array in any way you want, no need to use explode().
$ids = [1, 2, 3];
$results = Post::whereIn('posts_id', $ids)->get();
It may be good to check if the array isn't empty before making that query.
This question already has an answer here:
Input my php in mysql without repeat?
(1 answer)
Closed 9 years ago.
I want to add some random number that created by PHP to my SQL without repeat.
I use this code to create 14 length random:
for ($i=0;$i<10;$i++) {
$n1 = rand(100000,999999);
$n2 = rand(100000,999999);
$pincode = (string)$n1.(string)$n2;
echo $pincode;
echo nl2br("$pincode\n");
Now I want to input created a number in My SQL and ignore the repeated number.
How can I do that ?
The best way is to use timestamp. It shall always be unique and no chance of duplicacy.
Afroz, timestamp is probably unique, but very predicteable ;-)
This might be interesting: How to 'insert if not exists' in MySQL?