I am trying to generate a unique String with a function. feed the output into a different function that checks a database with PDO to see if that String of characters already exists and then parse it to be entered into a database using PDO. IF for some reason the query comes up positive the function that generates the String gets called again and the process repeats itself. ( on a side note this is why I need this to be done via functions; so I can recall the function over and over if I need to, if you have any better ideas please do share)
my code
$pdo = new PDO("mysql:host=localhost;dbname=notifiyr;charset=utf8mb4", 'root', '', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
$length = 10;
function generatecode($length,$pdo){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$abc = $randomString;
checkcode($abc);
}
function checkcode($abc){
$sql2 = "SELECT id FROM users WHERE code = :code";
if($stmt = $pdo->prepare($sql2,$abc,$pdo)){
$stmt->bindParam(":code", $param_code, PDO::PARAM_STR);
$param_code = $abc;
if($stmt->execute()){
if($stmt->rowCount() == 1){
generatecode();
} else{
$code = $abc;
}
} else{
$code_err = "something doest want to work here, come back later";
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
}
the problem I am having is that later on in the script I am supposed to enter this along with other variables into the database using PDO all of them enter but the randomly generated string.
edit
I changed my code to this
function generatecode($length,$pdo){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$abc = $randomString;
return $abc;
}
function checkcode($abc,$pdo){
$sql2 = "SELECT code FROM users WHERE code = :code";
if($stmt = $pdo->prepare($sql2,$abc,$pdo)){
$stmt->bindParam(":code", $param_code, PDO::PARAM_STR);
$param_code = $abc;
if($stmt->execute()){
if($stmt->rowCount() == 1){
generatecode();
} else{
$code = $abc;
return $code;
}
} else{
$code_err = "something doest want to work here, come back later";
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
}
generatecode($length,$pdo);
checkcode($abc,$pdo);
I've had trouble returning functions before in PHP, I hope this code is better
The problem is that you are not using functions correctly, not only are you not parsing items incorrectly you are calling them incorrectly. read the documentation more carefully.
I think you would be want something like this
function generatecode($length,$pdo){
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$abc = $randomString;
return checkcode($abc,$pdo);
}
function checkcode($abc,$pdo){
$sql2 = "SELECT code FROM users WHERE code = :code";
if($stmt = $pdo->prepare($sql2)){
$stmt->bindParam(":code", $param_code, PDO::PARAM_STR);
$param_code = $abc;
if($stmt->execute()){
if($stmt->rowCount() == 1){
generatecode();
} else{
$code = $abc;
return $code;
}
} else{
$code_err = "something doest want to work here, come back later";
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
}
$code = generatecode($length,$pdo);// this correctly calls the function
you're welcome
Related
$query1 = "INSERT INTO `user_order` (user_id,product_id,cart_id,product_name,product_quantity,number_of_item,total,shipping_charge,discount,total_net_amount) VALUES
('$user_id','$Productid','$Cartid','$Product_name','$Quantity','$Total_Number_of_Items','$Total','$Shipping_charge','$Discount','$Total_amount')";
$run_product = mysql_query($query1);
$last_id = mysql_insert_id();
Use LAST_INSERT_ID() function
SELECT LAST_INSERT_ID() from user_order;
i find out solution...
Add to RandomString
Post.php
function generateRandomString($length = 30) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
if(){$dataObj->generateRandomString());}else{
echo ResponseClass::successResponseInArray("data", null, "0" ,"data missing","False");}}
then apiclass.php pass values
$sql = "SELECT * FROM user_order WHERE user_id = '$user_id' AND product_id = '$Productid' AND r_number = '$generateRandomString'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$only_last_id = $row['order_id'];
** find out last insert ID :)
LAST_INSERT_ID() should do the trick in a mysql console . though i would strongly suggest you to not use the old mysql connector you are currently using and Switch to PDO.
I need to generate a random string when I insert data in my mysql.
I did read about uuid or cast(rand) but I cant find anything that looks like I can use it.
My data comes from a app.
I made a new row called code and made it unik.
I hope you can help me :)
how do I tell my insert to generate a random string to my row code?
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['nummer']) && isset($_POST['description']) && isset($_POST['dato'])) {
$name = $_POST['name'];
$nummer = $_POST['nummer'];
$description = $_POST['description'];
$dato = $_POST['dato'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mysql_set_charset("utf8");
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato) VALUES('$name', '$nummer', '$description', '$dato')");
Ok this is what I got so far
if (isset($_POST['name']) && isset($_POST['nummer']) && isset($_POST['description']) && isset($_POST['dato'])) {
$name = $_POST['name'];
$nummer = $_POST['nummer'];
$description = $_POST['description'];
$dato = $_POST['dato'];
// $code = $_POST['code'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
function generate_random_string($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato, code) VALUES('$name', '$nummer', '$description', '$dato', '$randomString')");
But I dont get anything in my code row?
return $randomString;
$random_str = generate_random_string(10);
}
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato, code) VALUES('$name', '$nummer', '$description', '$dato', '$random_str')");
You can generate a random number using PHP's function rand :
// code = rand($min , $max); for example
code = rand(100000, 999999); // will generate a number between 100000 and 999999
// then add the column to your insert if it belongs to the same table or
// make another query to insert the code if it belongs to a different table
note that you can use the current time and md5 function to make stronger unique codes.
Also, if you like to take this logic to your database, try to create a trigger that will runs after each insert.
Good luck.
You can try the code below:
function generate_random_string($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
echo generate_random_string(15); // define amount of string length in parametre
Source: PHP random string generator
If you use random number as Random String code is below:
$number = range(100000,999999);
shuffle($number);
$ran_string = $number[0];
echo $ran_string;
I'm working on a domain shortening service called "sHTTP". It uses a MySQL database to store the shortened URLs. I can't insert them though.
Here's my code:
function db(){
$link = mysqli_connect('sqlserver', 'user', 'pass', 'db') or die(mysqli_error());
return $link;
}
$url = mysqli_real_escape_string(db(), $_POST['url']);
$ip = $_SERVER['REMOTE_ADDR'];
function checkexists($name){
// check if shttp exists
$q = mysqli_num_rows(mysqli_query(db(),"SELECT name FROM shttp WHERE name = '$name'"));
if($q > 0){
return true;
} else {
return false;
}
}
function generateRandStr($length){
// generate string for placeholder name
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
if(checkexists($name)){
die('sHTTP name exists already!');
}
if($_POST['url'] == ''){
die('No URL entered!');
}
if(!$_POST['name']){
$name = generateRandStr(5);
}else{
$name = mysqli_real_escape_string(db(), $_POST['name']);
}
//THIS IS MY MAIN PROBLEM HERE GUISE
$query = "INSERT INTO shttp(name, url, ip) VALUES ($name, $url, $ip)";
//Y U NO WORKING
$exe = mysqli_query(db(), "INSERT INTO shttp (name, url, ip) VALUES ($name, $url, $ip)");
if(!$exe){
//I'M GETTING THE DIE HALP
die('Error: Could not be processed');
} else {
echo 'sHTTP created!<br>URL: <a href=http://shttp.tk/ '.$name.'>http://shttp.tk/'.$name.'</a>';
}
I'm getting the "Error: Could not be processed" I set up.
Also, my DB table is this:
name varchar(255)
url varchar(255)
ip varchar(255)
I believe that's how I set it up in my code as well.
If anyone can help, I would appreciate it. Thank you for your time.
You need to use quote for the string values as
$query = "INSERT INTO shttp(name, url, ip) VALUES ('$name', '$url', '$ip')" ;
I have the following PHP function that attempts to register a user in a database with a temporary password when they post an email adress via a form:
public function registerNewUser() {
$temp_pass = '';
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$random_string_length=8;
for ($i = 0; $i < $random_string_length; $i++) {
$temp_pass .= $characters[rand(0, strlen($characters) - 1)];
}
if (empty($_POST['user_email'])) {
$this->errors[] = FEEDBACK_EMAIL_FIELD_EMPTY;
} elseif (strlen($_POST['user_email']) > 64) {
$this->errors[] = FEEDBACK_EMAIL_TOO_LONG;
} elseif (!filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL)) {
$this->errors[] = FEEDBACK_EMAIL_DOES_NOT_FIT_PATTERN;
} elseif (!empty($_POST['user_email'])
&& strlen($_POST['user_email']) <= 64
&& filter_var($_POST['user_email'], FILTER_VALIDATE_EMAIL)) {
$this->user_email = htmlentities($_POST['user_email'], ENT_QUOTES);
$this->user_password = $temp_pass;
$this->hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
$this->user_password_hash = password_hash($this->user_password, PASSWORD_DEFAULT, array('cost' => $this->hash_cost_factor));
$sth = $this->db->prepare("SELECT * FROM users WHERE user_email = :user_email ;");
$sth->execute(array(':user_email' => $this->user_email));
$count = $sth->rowCount();
if ($count == 1) {
$this->errors[] = FEEDBACK_USEREMAIL_ALREADY_TAKEN;
} else {
$this->user_activation_hash = sha1(uniqid(mt_rand(), true));
$sth = $this->db->prepare("INSERT INTO users (user_email, user_password_hash, user_activation_hash) VALUES(:user_email, :user_password_hash, :user_activation_hash) ;");
$sth->execute(array(':user_email' => $this->user_email, ':user_password_hash' => $this->user_password_hash, ':user_activation_hash' => $this->user_activation_hash));
$count = $sth->rowCount();
if ($count == 1) {
$this->user_id = $this->db->lastInsertId();
// send a verification email
if ($this->sendVerificationEmail()) {
// when mail has been send successfully
$this->messages[] = FEEDBACK_ACCOUNT_SUCCESSFULLY_CREATED;
$this->registration_successful = true;
return true;
} else {
$sth = $this->db->prepare("DELETE FROM users WHERE user_id = :last_inserted_id ;");
$sth->execute(array(':last_inserted_id' => $this->db->lastInsertId() ));
$this->errors[] = FEEDBACK_VERIFICATION_MAIL_SENDING_FAILED;
}
} else {
$this->errors[] = FEEDBACK_ACCOUNT_CREATION_FAILED;
}
}
} else {
$this->errors[] = FEEDBACK_UNKNOWN_ERROR;
}
// standard return. returns only true of really successful (see above)
return false;
}
I keep tripping the FEEDBACK_ACCOUNT_CREATION_FAILED error, but can't figure out why. Any ideas?
Have you dumped "$sth" after it does the insert?
What does that give you?
If you are using mysql you can turn the general_log (http://dev.mysql.com/doc/refman/5.1/en/query-log.html) to see the mysql query that gets executed.
This way you can see if the query is getting created properly.
Turning on mysql logging can be very useful if you are not sure whats happening at the other end.
Below is my code that i have written to create a random string. Works well. It also checks to make sure that the generated string doesn't already exist, and if it does, then it makes another one. HOWEVER i haven't yet worked out a way to make the code generated if one already exists be checked to see if that one exists. Would i be best doing an elseif statement?
PHP
<?PHP
require_once('dbConfig.php');
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 12; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
//$generatedId = "SPI-E7HN2SBIIF5W";
$generatedId = 'SPI-'.$randomString;
//Prepare select query
$statement = $db->prepare("SELECT client_unique_id FROM clients WHERE client_unique_id = ? LIMIT 1");
//Determine variable and then bind that variable to a parameter for the select query ?
$id = $generatedId;
$statement->bind_param('s', $id);
//Execute and store result so that num_rows returns a value and not a 0
$statement->execute();
$statement->store_result();
//Bind result to a variable for easy management afterwards
$statement->bind_result($clientId);
// Generate a random ID for the user if the previously generated one already exists
if($statement->num_rows > 0){
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 0; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
$generatedId = 'SPI-'.$randomString;
echo $generatedId;
} else {
// If there's no issue with what's been created, echo it out :)
echo $generatedId;
}
?>
Any help is appreciated :)
try this.
// initialize a variable to hold the last generated id,
$generatedId = '';
// and another to hold the returned client_unique_id,
$clientId = '';
setup your prepared statement
bind the parameter,
$statement->bind_param('s', $id)
do
{
generate a new Id. (Code for generating random id goes here).
$generatedId = '...';
// bind the generated id to the prepared statement.
$id = $generatedId
// execute the prepared statement,
$statement->execute()
// fetch the results into $clientId
$statement->bind_result($res);
while($statement->fetch()) {
$clientId = $res;
}
} while ($clientId != '');
$statement->close();
// echo the last generated Id
echo $generatedId;
cheers,
William