PHP, generate string with format, check against SQL db? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to use PHP as a way to process this in a webpage, my typical language is java so i am unfamiliar with how this would be done for product keys.
This is basically the process:
1. Generate random string with format XX-XXXX-XXXX-XXX a mix of numbers and letters.
2. Check if it already exists in an SQL database
3. If exists, generate another one and repeat?
So how would I do this using PHP?
Please explain what i would need to do and what is the best way of going about it.

Generate random string from following function.
<?php
function randomString() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
$array_lengths = array(2,4,4,3);
foreach($array_lengths as $v){
for ($i = 0; $i < $v; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
$pass[] = '-';
}
return rtrim(implode($pass),'-'); //turn the array into a string
}
echo randomString();
?>
SQL
Please create unique key field and use ON DUPLICATE KEY query for insert/ update data
DEMO

You can generates randomnumbers key using this way.
echo rk(2)."-".rk(4)."-".rk(4)."-".rk(3);
function rk($chars) {
$letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
return substr(str_shuffle($letters), 0, $chars);
}

Here's a process that could be of use!
<?php
/** The function below was taken from http://stackoverflow.com/questions/853813/how-to-create-a-random-string-using-php **/
function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'){
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str;
}
/** The function that will do your work is: **/
function theProcess(){
/** Now to inefficiently concatenate your random string together. **/
$theString = randString(2)."-".randString(4)."-".randString(4)."-".randString(3);
echo $theString;
/** Proceed to query your database using MySQLi or PDO, with a query similar to: **/
/** Add your preliminary (connection) code here. **/
$sthandler = $dbhandler->prepare('SELECT 1 FROM products WHERE productKey = ?');
$sthandler->execute(array($theString));
/** Check whether a result is returned from MySQL. **/
if ($sthandler->rowCount() > 0) {
exit("IT EXISTS!");
} else {
theProcess();
}
}
/** Call the function the first time. **/
theProcess();
?>

Related

check if record exist in Laravel 5.5 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a dynamic input form, I want to check if the record exists, if no then it can not insert data
my controller
$user = Master::where('id_a','=',$request->get('id_a'))->where('id_b','=',$request->get('id_b'))->get();
if($user->isEmpty()){
// insert
}else{
//message "cannot input"
}
if insert one data, success.. but if insert array in my controller not check..
why in input array data always insert???
This is pseudo for only check id_b
$data = [1,2,3,4];
$data_a = [1,2,3,4];
$masters = Master::whereIn('id_b', $data)->whereIn('id_a', $data_a)->get();
foreach($data as $key => $value) {
$isExisted = false;
foreach ($masters as $master) {
if ($master->id_b == $value[$key] && $master->id_a == $data_a[$key])
{
$isExisted = true;
break;
}
}
if ( ! $isExisted) {
$master = new Banner();
$master->value = your_data;
$master->save();
}
}
You could use exists()
if(Master::where('id_a','=',$request->get('id_a'))->where('id_b','=',$request->get('id_b'))->exists()) {
do something
}
Also I would suggest you reduce the amount of in-line stuff you're doing, instead something like this:
$id_a = $request->get('id_a');
$id_b = $request->get('id_b');
if(Master::where('id_a','=', $id_a)->where('id_b','=',$id_b)->exists()) {
do something
}
If I understand correctly, you want to insert a Master if a given id_a and id_b doesn't already exists for one Master
If so, you could actually use firstOrCreate :
Master::firstOrCreate(
['id_a' => $request->get('id_a'), 'id_b' => $request->get('id_b')],
['yourcolumntocreate' => columnvalue, ...]
)

How to generate voucher code, check the DB if it's unique, generate new one if not

I'm having a loop issue in my script. I've spent a lot of time trying to fix it but I still don't know how to fix the problem. I need your help and suggestions regarding this.
My goal is to create a voucher code generator script where the user enters the number of voucher codes to be generated.
Then, the script will generate the required number of vouchers in the database table, and each voucher code will be checked if it is unique - if not, a new voucher code will be generated and the script will proceed until all vouchers are saved.
The problem is that if voucher already exists in the DB, a new one needs to be generated. This newly generated voucher code needs to be checked again if it's already in the DB, if it's unique it will be saved to the DB and if not, the process will go on again. This is where the loop problem lies. I hope you get what i mean.
By the way, the voucher code is in this format: XXXX-XXXX-XXXX (uppercase letters only)
Here's the current codes that I have:
include 'conn.php';
function WriteCSV($flname,$values) {
$Filename = "./vouchers/$flname.csv";
$fh = fopen($Filename, 'a') or die("can't open file");
$filecontent = $values;
$filecontent .= PHP_EOL;
fwrite($fh,$filecontent);
fclose($fh);
}
function generateCode(){
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$res = "";
for ($i = 0; $i < 4; $i++) {
$res .= $chars[mt_rand(0, strlen($chars)-1)];
}
return $res;
}
function generateVCode(){
$c1 = generateCode();
$c2 = generateCode();
$c3 = generateCode();
$voucher = "$c1-$c2-$c3";
return $voucher;
}
function searchDB($con, $voucher){
$rs = mysqli_query($con,"SELECT count(*) AS cnt FROM vouchers WHERE vouchercode = '$voucher'");
$row = mysqli_fetch_assoc($rs);
$cnt = $row['cnt'];
if($cnt > 0){
return '1';
} else {
return '0';
}
}
function checkVoucher($con, $voucher, $vsource, $expiry, $today, $vnum, $vprice){
$dbres = searchDB($con, $voucher);
if($dbres == '1'){ //voucher found in db
$val = '0';
$voucher = generateVCode(); //generate a new voucher
checkVoucher($con, $voucher, $vsource, $expiry, $today, $vnum, $vprice); //repeat the process
} else { // voucher is unique
mysqli_query($con, "INSERT INTO vouchers (vouchercode, source, price, expires, generated) VALUES ('$voucher', '$vsource', '$vprice', '$expiry', '$today')");
$flname = "$vsource - ".date('d M Y')." ($vnum vouchers)";
WriteCSV($flname,$voucher);
$val = '1';
}
return $val;
}
$vnum = $_POST['vouchernum'];
$vsource = $_POST['source'];
$vprice = $_POST['amt'];
$expdate = $_POST['expdate'];
$expiry = $_POST['voucherexpiry'];
$today = date('Y-m-d');
$expconv = date('Y-m-d',strtotime("$expiry"));
$expfive = date('Y-m-d',strtotime("$expiry +5 years"));
for ($x = 1; $x <= $vnum; $x++) {
$vouchercode = generateVCode();
if($expdate == "no"){
$expiry = $expfive;
} else {
$expiry = $expconv;
}
do {
$result = checkVoucher($con, $vouchercode, $vsource, $expiry, $today, $vnum, $vprice);
} while ($result != '1');
header("location: index.php?s=1");
}
By the way, if you have suggestions on how to generate the voucher codes easier, please feel free to share.
I'm thinking the issue/problem here is on either the do-while statement or the checkVoucher() function.
I'd really appreciate you help and suggestions. Thanks.
I would go completely easier. Set the voucher column in your table to unique. Generate a code PHP side, do your insert, in the error callback function call to generate a new code.
Basically, this will self loop until inserted. Then in your success callback add it to your display. All of this is wrapped in a while loop. Once you get your 5, break the loop.
As far as generating a random string with minimal chance of a repeat, check this thread: PHP random string generator
I would generate the full length string and then just add your hyphens.
Using this approach to generate random unique data, the amount of processing required increases proportionally as more and more codes are generated.
What I would do instead is:
Generate a whole bunch of values (lets say a few thousand) values sequentially and store them in a redis/SQL database
Use a random number to index that record in the database, and remove the record from the table once it has been used
This reduces the processing required greatly, and also gives you a pre determined pool of voucher codes which could be useful for other purposes in your application
Mysql unique constraint may be the solution you are looking for.it ensures a value is always unique. It is like primary key. but unlike primary key a table can have multiple unique values.
Here is the link to w3school explaining this
www.w3schools.com/sql/sql_unique.asp
The best part is it will genrerate a Duplicate Entry error when adding a duplicate entry. so you can use it to add data to csv . add it only when you have no error.
But make sure the unique value is not null.

Get a length of a php's result [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I don't know php at all so sorry for a simple question - I've got the project started by another person so now I'm trying to finish it.
The problem is - I'm making an android app for which I can't make a change without changing a php and this language I don't know.
here's this part :
function getPlaces(){
$result = array();
$sql = "SELECT id, name, short_description, photo_list, selected, recommended, isTOP FROM place
WHERE id IN(SELECT id_place FROM rubric_place WHERE id_rubric IN(SELECT id FROM rubric WHERE name = '".$_REQUEST["rubric"]."')) ORDER BY isTOP DESC";
getConnect();
$query = mysql_query($sql);
if(!$query){
error100();
}else {
$result['code'] = 200;
for ($i = 0; $i < mysql_num_rows($query); $i++) {
$row = mysql_fetch_assoc($query);
$result["places"][$i] = $row;
$sql = "SELECT * FROM rubric WHERE id IN(SELECT id_rubric FROM rubric_place WHERE id_place = ".$row[id].")";
$queryModule = mysql_query($sql);
if($queryModule){
for ($k = 0; $k < mysql_num_rows($queryModule); $k++) {
$rowModule = mysql_fetch_assoc($queryModule);
$result["places"][$i]["rubrics"][$k] = $rowModule;
}
}
$sql = "SELECT SUM(rating)/COUNT(rating) AS rating FROM comment WHERE id_place = ".$row[id];
$queryModule = mysql_query($sql);
if($queryModule){
$rowModule = mysql_fetch_assoc($queryModule);
$result["places"][$i]["rating"] = $rowModule[rating];
}
}
echo json_encode($result, JSON_UNESCAPED_UNICODE);
exit();
}
}
what I need is to make another function that returns in $result a value of "length" of places. I know I can find out length on the other end - in Android's app result, but this particular function will be changed so it will return by 20 results only so I need another function that returns length so plz help
To count the number of characters in a json you can do:
$string = json_encode($result, JSON_UNESCAPED_UNICODE);
$length = strlen($string);
You have to first put the json into a variable to count it, before outputting it.
To count the items in an array before you turn it into a json, you can do:
$length = count($array);

Next statement in a While Loop with PHP [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Ok i have a while loop function in my site that pulls in excel documents and parses them to the database i want to check for duplicates and if duplicate skip it:
$content = file($selectfile1);
$posted_content = array();
list($rownum, $row) = each($content);
$posted_content[0] = explode(",", $row);
array_push($posted_content[0], "ID");
$count = 0;
// iterate each row (1 post)
while (list($rownum, $row) = each($content))
{
$count++;
$cols = "orderid, created_at, updated_at, notification_type, radius, available, expiration, ";
$vals = "";
$cols2 = "equipment_id";
$vals2 = "";
....{parsing data)...
}
i want to write in a script that checks to see if the record is a duplicate and if not enter it.
$sql25 = "SELECT * FROM notifications WHERE origin =" . $origin_id . " user_id =12039";
$rs25 = $conn->Execute($sql25);
if($rs25->RecordCount() == 1 || $rs25->RecordCount() >= 1)
{
here is where i need a command. Can you use? next()
--------------------------------------------------
}
else
{
Insert query
}
You are looking for the continue statement.
From the docs:
continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
(See http://www.php.net/manual/en/control-structures.continue.php)
example:
<?php
while ( ... ) {
if ($foo = 'bar') {
// skip to the next iteration
continue;
}
}

equivalent to foreach loop for just one row [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a PHP function that runs a SELECT Query in SQL:
if(!function_exists("SelectQuery")) {
function SelectQuery ($sql) {
global $conn;
$SelectQuery = mysql_query($sql,$conn);
return $NumRows=mysql_num_rows($SelectQuery);
$SelectQuery_Results=array();
while($SelectQuery_Row = mysql_fetch_array($SelectQuery)) {
$SelectQuery_Results[] = $SelectQuery_Row;
}
return $SelectQuery_Results;
}
}
then i am calling it here:
$sql="SELECT * from tickets where ticketnumber = '".$_GET["seq"]."' ";
$ticket = SelectQuery($sql);
foreach($ticket as $ticket2) {
}
rather than using a foreach loop what else could i use as my query will only be returning one row and i dont want to put my whole page within a loop
i tried just removing the foreach loop but that didnt work
Just access your value as $ticket[0].
A function cannot return two values for a single call. So, remove
return $NumRows=mysql_num_rows($SelectQuery);
You can check the array size for the number of rows in result.
If you want to echo out the result the following code will be ok!
if( sizeof($ticket) > 1 ){
foreach($ticket as $ticket2){
for($i=0; $i<sizeof($ticket2)/2; $i++)
echo "[" . $ticket2[$i] . "]";
echo "<br />";
}
}
$ticket is an integer see :
return $NumRows=mysql_num_rows($SelectQuery);
So you juste have to use $ticket.
If you want the row, remove this useless return in the SelectQuery function and use $ticket[0] for the first and only row.
Change the function with this :
function SelectQuery ($sql) {
global $conn;
$SelectQuery = mysql_query($sql,$conn);
$NumRows=mysql_num_rows($SelectQuery);
$SelectQuery_Results=array();
if ($numRows>1) {
while($SelectQuery_Row = mysql_fetch_array($SelectQuery)) {
$SelectQuery_Results[] = $SelectQuery_Row;
}
}
else $SelectQuery_Results = mysql_fetch_array($SelectQuery);
return $SelectQuery_Results;
}
Then use :
$sql="SELECT * from tickets where ticketnumber = '".$_GET["seq"]."' ";
$ticket = SelectQuery($sql);
if (is_array($ticket)) { foreach loop; }
else { use directly ticket['attribute'] }

Categories