Php Serial Number Generator - php

I'm currently creating a serial number generator, but the problem is the input right now is just sorting the number that i input, i wanna shuffle the number of the input like example if i input : 1000 - 1100
the output to the database are: 1050,1010,and go on but the count still for 100 serial generated.
Check in my database if this Serial exist, if it does,regenerate another
Here's The Code in my php right now.
{
if(!empty($_POST['sr_number'])){
echo $sql = "insert into product_serials set sr_number='".$_POST['sr_number']."', product_name='".$_POST['product_name']."', brand='".$_POST['brand']."'";
$rs = mysqli_query($con, $sql);
if($rs){
header("location: dashboard.php?msg=success");
}
}else if($_POST['sr_start'] !="" and $_POST['sr_end']!=""){
if($_POST['sr_end']>$_POST['sr_start']){
for($i=$_POST['sr_start']; $i<=$_POST['sr_end']; $i++){
$sql = "insert into product_serials set sr_number='".$i."', product_name='".$_POST['product_name']."', brand='".$_POST['brand']."'";
$rs = mysqli_query($con, $sql);
}
}
header("location: dashboard.php?msg=success");
}
}

Related

Trying to insert a random six digit code/number in mysql table but it is giving same for every new registered users

I am trying to insert 6 digits number in mysql table through php but every time I tried to register a new user, it is giving the same sequence of code.
I have done something like this
<?php
if(isset($_POST['generate']))
{
$num = (rand(111111, 999999));
file_get_contents("mylink");
$query = mysqli_query($con, "UPDATE users SET otp='".$num."'");
$qry_run = mysqli_query($con, $query);
header("location: otp.php");
}
?>
Because You Are not Put Any Condition in Your Query.
So now it will update all users and set same random number to all fields.
Build Query Like this
$query = mysqli_query($con, "UPDATE users SET otp='".$num."' WHERE USERID = 1 ");

Create a "Secret Santa" generator using MySQL and PHP

I am trying to create a Secret Santa system using a PHP page and a MySQL database to store the details so if someone forgets their match they can re-request it.
Step 1: I created a random number generator based on the number of people in the list in the database.
Count Function:
$maxSQL = "SELECT COUNT(id) as total FROM secretsanta";
$maxRS = mysqli_query($conn, $maxSQL);
$maxQuery = mysqli_fetch_array($maxRS);
$maxpersons = $maxQuery['total'];
Then the Random Number Generator:
$assigned = rand(1,$maxpersons);
Step 2: Test if the random number matches the persons own id and regenerate a new number if true.
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id);
Step 3: Write the paired id to the persons database record.
$assignSQL = "UPDATE secretsanta SET assigned = '".$assigned."' WHERE secretsanta.id = ".$id;
if (mysqli_query($conn, $assignSQL)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
The Problem: Now I need to check that other people aren't assigned to that person or otherwise some could miss out and others would get more than others.
I tried to implement a function that contained a query to test each record to see if that number already existed and was hoping to add it as a condition to perhaps a while or do while statement?
if (!function_exists('checkRandom')){
function checkRandom($funcid){
$Check_SQL = "SELECT assigned FROM secretsanta ORDER BY id ASC";
$Check_RES = mysqli_query($conn, $Check_SQL);
if (Check_RES) {
while ($CheckArray = mysqli_fetch_array($Check_RES, MYSQLI_ASSOC)) {
$CheckAsgn = $CheckArray['assigned'];
if ($funcid==$CheckAsgn) {return true;}else{return false;}
}
}
}
}
Then implement it into the do while statement like this:
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id||checkRandom($assigned));
No luck so far...HELP!.. please :)
P.S. I know there are websites that already do this, I just don't trust them to give out mine and family email address' if I can make my own private version myself.
Using your method, the first few assignments will be done with no problem, but imagine the last unassigned entry and how many times it will try a random number only to find the person with that id is already assigned..
I'm gonna give you another approach to your problem: for each user that you want to assign a santa to, make a new SELECT statement with a WHERE clause that lets you select only those users that are not assigned yet.
check out my code and see if that helps you. I just typed this and didnt test it so there could be some mistakes.
// load all unassigned users into an array
$unassignedUsers = [];
$query = "SELECT id, assigned FROM secretsanta WHERE assigned is NULL";
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedUsers[] = $row;
}
if(count($unassignedUsers) == 1){
echo 'There is only 1 unassigned user. Therefore he cannot be matched';
} else {
// for loop for each user in DB that is not assigned yet
//for ($i = 1;$i <= count($unassignedUsers); $i++){
$i = 0;
foreach($unassignedUsers as $user)
// if its the second-to-last iterations of the for-loop, check for legality of the last one
if(count($unassignedUsers) - $i == 1){
$lastUserID = $unassignedUsers[count($unassignedUsers)-1]['id'];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id = ".$lastUserID;
$res = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($res);
if ($rowcount){
// last user is still unassigned
$query = "UPDATE secretsanta SET assigned = '".$lastUserID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
} else {
// select all unassigned users
$unassignedIDs = [];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id <> ".$user['id'];
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedIDs[] = $row['id'];
}
// get a random id from $unassignedIDs
$randomIndex = rand(0, count($unassignedIDs)-1);
$randomID = $unassignedIDs[$randomIndex];
// assign $randomID to user
$query = "UPDATE secretsanta SET assigned = '".$randomID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
$i++;
}
}
last edit: refactored whole code so it is able to be run multiple times and only assigns new users who are not assigned yet.
Step 1 is dependent on have a contiguous set of ids for the people. Think what happens if '3' leaves the company and it hires 6 to replace them....1,2,4,5,6 ($maxpersons=5)
"Now I need to check" - no you are still trying to solve the problem by guessing then seeing if your guess worked. Use an algorithm which is always going to return a correct result. The method below requires the addition of a temporary field 'sequence' of type float.
mysqli_query($conn,"UPDATE secretsanta SET sequence=RAND()");
$first=false;
$prev=false;
$all=mysqli_query($conn, "SELECT * FROM secretsanta ORDER BY sequence, id");
while ($r=mysqli_fetch_assoc($all)) {
if (false===$first) {
$first=$r['id'];
} else {
save_pair($prev, $r['id']);
}
$prev=$r['id'];
}
save_pair($prev, $first);
(but with better error checking)

MYSQLI row updating by 2 when update by 1 is called

i have a curious problem. When i make an update to a row, the info is updated, but not how i expect it to. i call this code
$count = $v_count+1;
mysqli_query($db_conn, "UPDATE videos SET v_count='$count' WHERE id='$vk'");
I have also tried this code as well...
if(isset($_POST['vk'])){
mysqli_query($db_conn, "UPDATE videos SET v_count='$v_count'+1 WHERE id='$vk'");
}else{
echo mysqli_error($db_conn);exit();
}
It does work, But the number is increased by 2, not the 1 i expected.This line HAS worked in other applications i have used... but now it is behaving oddly. Any help will be appreciated. Here is the full PHP block
$vk = $_GET['vk'];
if($vk != ''){
$sql = "SELECT * FROM videos WHERE id='$vk' LIMIT 1";
$query = mysqli_query($db_conn, $sql) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)) {
$v_count = $row['v_count'];
}
mysqli_query($db_conn, "UPDATE videos SET v_count=v_count+1 WHERE id='$vk'");
mysqli_free_result($query);
}else{
header('location: index.php');
}
You probably have some error in your application logic such that $v_count in your PHP code doesn't equal the v_count field in your MySQL table.
If you use
mysqli_query($db_conn, "UPDATE videos SET v_count=v_count+1 WHERE id='$vk'");
it will always increase by 1 no matter what the value of your $v_count PHP variable.

PHP redirect syntax utilizing results of mysqli query

I have a database table with six records which are urls for six different shiny servers. There is a program that populates, on a real time basis, whether each of the servers are available. I have written a query that returns the url of the first available server. I have tested the script and determined the selection process works. I now want to perform a redirect to the available server using the "header" function and I am having difficulty determining the correct syntax. The URLs are in the format of "muscle.mysite.com:3535nameScan." Here is what I have at present.
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 ";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
//printf ("%s\n", $row["url"]);
$url= printf ("%s\n", $row["url"]);
header ("Location: $url"); //redirect to muscle*
mysqli_close($dbc);
exit(); //before or after mysqli_close? I think after.
When I execute, I see mysite.com/40 in the address bar and I get a 404.
I tried this:
header ("Location: $row"); //redirect to muscle*
When I execute, I get "mysite.com/array in the address bar and I get my 404 page. I have tried many variations and I have thoroughly confused myself.
I hope you can see what I am trying to do. I have backed up to what does work which is
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 ";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
printf ("%s\n", $row["url"]);
mysqli_close($dbc);
I get the first url that is available and I can see the results printed as muscle.mysite.com:3535nameScan. Now, I need to capture the results as a variable I can use in an UPDATE query and the header function. I have been searching for an answer and I have not found one as yet. I thought a different fetch command would be the answer but I could not find one that would apply to what I want to do.
I believe I am heading in the correct direction my using the suggestion to use "sprintf." However, I am still not able to "update" the table. Here is where I am at now.
error_reporting(E_ALL);
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 "; //make query
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
//printf ("%s\n", $row["url"]);
$url= sprintf ("%s\n", $row["url"]); //assign results to a variable?
echo "$url";
$qu = "UPDATE ShinyServers SET Availability = 0 WHERE url = $url LIMIT 1";
$ru = mysqli_query($dbc, $qu);
if (mysqli_affected_rows ($dbc) ==1){
echo '<p> The status has been updated</p>';
}else{
echo '<p class="error"> The status could not be updated</p>';
}
I get the expected results from 'echo "$url";' But I am getting the error message "The status could not be updated." I have been at this for so long I am afraid I am overlooking something. Is there a problem with the code or could there be a problem with the DB table? I looked at the DB table, created by someone else, and I noticed it does not have a unique column.
With prodigitalson and Dan08's help, I have a script that works. It is as follows
error_reporting(E_ALL);
$q = "SELECT url FROM ShinyServers WHERE Availability = '1' LIMIT 0, 1 "; //make query
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
//printf ("%s\n", $row["url"]);
$url= sprintf ("%s", $row["url"]); //assign results to a variable
//echo "$url";
$qu = "UPDATE ShinyServers SET Availability = 0 WHERE url = '$url' LIMIT 1";
$ru = mysqli_query($dbc, $qu);
if (mysqli_affected_rows ($dbc) ==1){
echo ' The status has been updated';
}else{
echo ' The status could not be updated';
}
mysqli_close($dbc);
header ("Location: http://$url");
exit();
My DB table is updated and I am redirected (I know I do not need the conditional statement). I learned also that the "header" function had to be after mysqli_close. I found that in the php manual. A little more tweaking and then I have the task of marrying this script into a registration script and a login script. Whoppee...thanks again.
This is my final script and it works perfectly
<?php
//selecting available server and update status
include_once '../DB/test1DB.php'; //connect to DB
error_reporting(E_ALL);
$q = "SELECT url FROM ShinyServers WHERE Availability = '0' LIMIT 0, 1 "; //make query
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
$url = sprintf("%s", $row["url"]); //assign results to a variable
$qu = "UPDATE ShinyServers SET Availability = 1 WHERE url = '$url' LIMIT 1";
mysqli_close($dbc);
header("Location: http://$url");
exit();

Simple mysql Query to check if row exist

I want to show user if he liked a image or not..
for that I am creating php code
$userid=$_COOKIE['userid'];
$sql = "SELECT * FROM likes WHERE `user_id`='{$userid}'";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($query);
if($row){
echo "unlike";
}
else{
echo "like";
}
I can not do this for everything like 'tags', 'shares', 'comments', 'favourites' ...many
Isn't there anything simpler than this...?
Like say $row_check=mysqli_check_exist($table,$column_name,$userid);
use mysql fetch row method
$num_row = mysqli_num_rows($query);
if($num_row>0)
{
//add your code
}
else
{
//add your code
}
There are a lot of ways of doing this really but if you arnt going to use any more information then weither or not the user has liked it doing select * is a bad idea. The reason why is that you are asking the database to return the value of every column in that table.
Assuming its a small database its probably not a problem no but as your database gets bigger you are puting more load on it then you need you should try and only select the columns you need and intend to use. Ok in this case the userid is probably indexed and its only one row, but if you get in the habit of doing it here you may do it else where as well.
try this instead.
$userid=$_COOKIE['userid'];
$sql = "SELECT count(user_id) as total FROM likes WHERE `user_id`='{$userid}'";
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($query);
if( $row ['total'] > 0){
echo "unlike";
}
else{
echo "like";
}
This way we are just getting the total. simple and elegant
Use mysqli_num_rows($query) if > 0 exist
You simply need to count the available records using
mysqli_num_rows($query);
This will return a number (count) of available records
So simple put a check like this :
$userid=$_COOKIE['userid'];
$sql = "SELECT * FROM likes WHERE `user_id`='{$userid}'";
$query = mysqli_query($conn, $sql);
$count = mysqli_num_rows($query);
if($count>0){
echo "unlike";
}
else{
echo "like";
}

Categories