$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.
Related
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
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')" ;
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
I have a function that generates a random combination.
my function looks like this:
function random_gen($length) {
$random= "";
srand((double)microtime()*1000000);
$char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$char_list .= "abcdefghijklmnopqrstuvwxyz";
$char_list .= "1234567890";
// Add the special characters to $char_list if needed
for($i = 0; $i < $length; $i++)
{
$random .= substr($char_list,(rand()%(strlen($char_list))), 1);
}
return $random;
}
$new_url = random_gen(6);
Now i would like to have a while-loop that checks if $new_url already exist in my database...
And then insert the result like this:
mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')");
I got everything to work except the while-loop. and i just cant figure out how to do it...
define your code field as UNIQUE in your database
generate a code and run an INSERT
check with mysql_affected_rows() if the INSERT actually happened or not (i.e. code already present)
saves you a SELECT query
while ( true ) {
$new_url = random_gen(6);
mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')");
if ( mysql_affected_rows() )
break;
}
Use this random_generator
function random_gen($length) {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1];
}
return $string;
}
You don't need a while loop, just perform a query
mysql_query("SELECT COUNT(*) FROM lank WHERE code = {$new_url}");
It's pretty straight forward:
$sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
while($row['num'] > 0) {
$new_url = random_gen(6);
$sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
}
This should work, without repeating code:
while(true) {
$new_url = random_gen(6);
$sql = "SELECT COUNT(*) FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
if (!$row[0])
break;
}
Use the uniqid() function instead. It will always generate a random result.
If you need more security (i.e.: you don't want adjacent values), simply hash the output: sha1(uniqid()).