Autoincremented unique string id - php

I have read many answers on stackoverflow, but I haven't find anything related my issue.
This is my table:
`id` char(11) NOT NULL,
`element` varchar(32) NOT NULL,
I need to use an autoincremented unique string id of 11 chars ( case sensitive if possible ) and numbers as youtube does:
youtube.com/watch?v=j5syKhDd64s
youtube.com/watch?v=YVkUvTmDf3Y
youtube.com/watch?v=8BcDeoKLsaY
...
How could I do this with mysql/php ?

You probably want something like hashids. Their page also links to alternative solutions.
If that doesn't fit the bill, please describe your problem in more detail.

one way to do it is to use this function
function generateRandomString($length = 11) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
and then pass $randomString result to your query to add in DB.
EDIT :
if OP is looking for the string like he mentioned (aaaaaaaaaaa, aaaaaaaaaab, aaaaaaaaaac, aaaaaaaaaad) i recommend you to check out Theory of Computation .

This is my code which I Autoincremented my unique id string field.
case "Add":
$itemno = $_POST['itemno'];
$qty = $_POST['qty'];
$unitprc = $_POST['unitprc'];
$amt = $_POST['amt'];
$coopmemid = $_SESSION['kiosk']['is_coopmemID_kiosk'];
$totamt = 0;
$totitm = count($itemno);
$a_empgroid = array();
for($x=0; $x<$totitm; $x++) {
$Addquery = "INSERT INTO tb_empgrocery (coopmemID , date_ordered, item_no, qty_ordered, unit_price, amount)
VALUES ('$coopmemid',(NOW()),'$itemno[$x]','$qty[$x]','$unitprc[$x]','$amt[$x]')";
$atecCoop->query($Addquery);
$totamt+=$amt[$x];
$inserted_id = $atecCoop->insert_id;
array_push($a_empgroid,$inserted_id);
}
$Savequery = "INSERT INTO tb_empgroc_master (order_status, date_ordered, total_items, total_amount) VALUES ('Pending', (NOW()), '$totitm', '$totamt')";
$atecCoop->query($Savequery);
$empgrocmstid = $atecCoop->insert_id;
$orderno = date('y-m-').str_pad($empgrocmstid, 10, "0", STR_PAD_LEFT);
$sql = "UPDATE tb_empgroc_master SET order_no='$orderno' WHERE empgrocmstID='$empgrocmstid'";
$atecCoop->query($sql);
foreach($a_empgroid as $empgrocid) {
$sql = "UPDATE tb_empgrocery SET order_no='$orderno' WHERE empgrocID='$empgrocid'";
$atecCoop->query($sql);
}
break;
As you can see the field oder_no is a unique id (varchar 25)
Hope this helps :)

Related

How to insert or update multiple rows - PDO

I have a small problem with the request to the base of the PDO.
I want to insert or update fields in one request. I want insert a few records to DB, but if there are already 'file_name' fields with the selected name then just to update the other fields. Below paste my php code.
For example: I adding 5 records id_product (eg. 1) and various other fields.
Example fields recived from the $_post:
(id_product, alt, file_name, main_photo)
1, xxx, 1_1, 0;
1, xxx, 1_2, 0;
1, xxx, 1_3, 1;
my PHP code:
$query = "INSERT INTO product_image (id_product, alt, file_name, main_photo) VALUES ";
$part = array_fill(0, count($_POST['file_name']), "(?, ?, ?, ?)");
$query .= implode(",", $part);
$query .= " ON DUPLICATE KEY UPDATE alt=VALUES(alt), main_photo=VALUES(main_photo)";
$stmt = $this->_db->prepare($query);
$j = 1;
$im_null = 0;
for ($i = 0; $i < count($_POST['file_name']); $i++) {
$stmt->bindParam($j++, $_POST['id_product'], \PDO::PARAM_INT);
$stmt->bindParam($j++, $_POST['alt'][$i], \PDO::PARAM_STR);
$stmt->bindParam($j++, $profile->base64_to_jpeg($_POST['file_name'][$i], APP_ROOT . '/uploads/products/' . $_POST['id_product'] . '_' . $_POST['file_nr'][$i]), \PDO::PARAM_STR);
($_POST['main_photo'][$i] == 1) ? $stmt->bindParam($j++, $_POST['main_photo'][$i], \PDO::PARAM_INT) : $stmt->bindParam($j++, $im_null);
}
$stmt->execute();
In this query inserts works good, but doesn't update, which is the second part of the request.
Move $j = 1; inside loop as it is you keep on incrementing $j.
$im_null = 0;
for ($i = 0; $i < count($_POST['file_name']); $i++) {
$j = 1;

PHP MYSQL Automate Create Value

i have code like
$quota = 100;
$quotaperclass = 25;
for ($x = 0; $x <= $quota/$quotaperclass ; $x++) {
$sql = "INSERT INTO classroom (name) VALUES ('A')";
for ($y = 0; $y <= 25 ; $x++) {
$sql = "INSERT INTO classroomstudent (studen_id, class_id) VALUES ('', 'A')";
}
}
I want if quota per class 25, total quota div quota per class. in my case result is 4 and then automated create 4 class like A, B, C, D and then add every student to the class.
my question is.
how to change value name automated like
loop 1 is A
loop 2 is B
loop 3 is C
etc
and how to add every student into class automatically.
thanks
$range = range('A', 'Z');
$quota = 100;
$quotaperclass = 25;
for ($x = 0; $x <= $quota/$quotaperclass ; $x++) {
$sql = "INSERT INTO classroom (id, name) VALUES ('', '".$range[$x]."')";
}
Try this
$c = 'A';
for ($x = 0; $x <= $quota/$quotaperclass ; $x++) {
$sql = "INSERT INTO classroom (id, name) VALUES ('', '$c')";
$c++;
}

Get the value of a variable declared in a PHP function

I have 2 pages, "signup.php" and "globalfunctions.php". On signup.php, I get all of the info from the form submission, I hash the password (by appending a random string generated in globalfunctions.php), and I use the function executeSQL that I defined.
signup.php:
include('/home/www/portaldev.samgoodman.co/processes/globalfunctions.php');
$singleAppendString = generateRandomAppend(16);
$form_email = $_POST['email'];
$form_password = $_POST['password'];
$form_name = $_POST['name'];
$form_school = $_POST['schoolid'];
$form_grad = $_POST['gradyear'];
$form_ip = $_SERVER['REMOTE_ADDR'];
$password_with_hash = $form_password.$singleAppendString;
$hashedPassword = sha1($password_with_hash);
executeSQL("$nextUserQuery", "SELECT id FROM users ORDER BY id DESC LIMIT 0 , 1");
Here is where I would like to get the value of $nextUserQuery from the database, but I need to return the value in the function.
executeSQL("$insertUser", "INSERT INTO users (id, name, email, password, school_id, grad_year, lvl, signup_ip) VALUES ('".$calc_userid."', '".$form_name."', '".$form_email."', '".$hashedPassword."', '".$form_school."', '".$form_grad."', '0','".$form_ip."')");
executeSQL("$insertHash", "INSERT INTO vault (id, hash) VALUES ('".$calc_userid."', '".$singleAppendString."')");
globalfunctions.php
function generateRandomAppend($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
function executeSQL($varName, $query) {
global $varName;
$con=mysqli_connect("localhost", "hugopak1_spm", "Massavailable1", "hugopak1_spm");
$varName = mysqli_query($con, $query);
return $varName;
}
What you currently do is not the correct way to get the value returned by executeSQL function. Remove $varName parameter from executeSQL function
function executeSQL($query) {
$con = mysqli_connect("localhost", "hugopak1_spm", "Massavailable1", "hugopak1_spm");
$varName = mysqli_query($con, $query);
return $varName;
}
and declare a new variable that will hold the returned value
$nextUserQuery = executeSQL("SELECT id FROM users ORDER BY id DESC LIMIT 0 , 1");
In the above example, the value of $nextUserQuery is the value returned by executeSQL("SELECT id FROM users ORDER BY id DESC LIMIT 0 , 1"). You should apply the same thing to the other two lines as below
$insertUser = executeSQL("INSERT INTO users (id, name, email, password, school_id, grad_year, lvl, signup_ip) VALUES ('".$calc_userid."', '".$form_name."', '".$form_email."', '".$hashedPassword."', '".$form_school."', '".$form_grad."', '0','".$form_ip."')");
$insertHash = executeSQL("INSERT INTO vault (id, hash) VALUES ('".$calc_userid."', '".$singleAppendString."')");

Php insert/update multple row, using array and not a foreach

I’m wondering if this is possible, I’ve search and haven’t found anything so about to give up.
I’m looking to do the following for example, note i do not want to use a foreach as that converts it into single queries.
$a = (1,2,3);
$b = ('john','Rob','Stuffs');
$c = ('doe','roe','soe');
$sql = "update ppl set firstname = $b, lastname = $c where id = $a";
The same can be said for an insert.
$sql = "insert into ppl (firstname,lastname) value ($b,$c)";
The main reason I'm looking to do this is to optimise the db a bit. There are a lot of single queries that (if this method is possible) could be converted into 1 single query.
Thanks in advance.
if (count($a) <= 0)
return; // nothing to do
$sql = "INSERT INTO table (id, firstname, lastname) VALUES";
while (count($a) > 0)
{
$id = array_shift($a);
$fname = array_shift($b);
$lname = array_shift($c);
$sql .= sprintf("('%s', '%s', '%s'),", mysql_real_escape_string($id), mysql_real_escape_string($fname), mysql_real_escape_string($lname));
}
$sql = substr($sql, 0, -1); //remove last comma
$sql .= " ON DUPLICATE KEY UPDATE firstname=VALUES(fname), lastname=VALUES(lname)";
//run your sql
this will allow you to run all of them at once.
For update you can do as follows
$a = (1,2,3);
$b = ('john','Rob','Stuffs');
$c = ('doe','roe','soe');
$i=0;
foreach($b as $fname){
if( !empty($b[$i]))
{
$sql = "update ppl set firstname = '".$b[$i]."', lastname = '".$c[$i]."' where id = $a[$i]";
}
$i++;
}
and for insert you can try
$i=0;
$var = '';
foreach($b as $fname){
if( !empty($b[$i]))
{
$var .= "(".$a[$i].",'".$c[$i]."','".$b[$i]."') ";
}
$i++;
}
if(!empty($var)){
$sql = "insert into ppl(id,firstname,lastname) values ".$var;
}

SQLite last_insert_rowid using PHP

I have a problem using sqlite_last_insert_rowid in PHP.
CODE:
$database = new SQLiteDatabase('example.db');
$sql_1 = "INSERT INTO ex1(test1, test2) VALUES ('$test1','$test2')";
$database->queryExec($sql_1);
$ex1_ID = sqlite_last_insert_rowid($database);
$sql_2 = "INSERT INTO ex2 (ex1_ID, fname, lname) values ('$ex1_ID','$fname','$lname');";
$database->queryExec($sql);
I want to store ID from ex1 table to table ex2 in ex1_ID
CREATE TABLE ex1 (
ID INTEGER PRIMARY KEY,
test1 LONGTEXT,
test2 LONGTEXT
);
CREATE TABLE ex2 (
ID INTEGER PRIMARY KEY,
ex1_ID INTEGER,
fname LONGTEXT,
lname LONGTEXT,
FOREIGN KEY ( ex1_ID ) REFERENCES ex1 ( ID )
);
COMPLETE CODE:
$database = new SQLiteDatabase('example.db');
for ($i = 0; $i < 10; $i++) {
$test1 = "";
$test2 = "";
$lenght = rand(300, 400);
for ($x = 0; $x < $lenght; $x++) {
$test1 .= rand(0, 9);
$test2 .= rand(0, 9);
}
$sql_1 = "INSERT INTO ex1 (test1,test2) VALUES ('$test1','$test2')";
$database->queryExec($sql_1);
$ex1_ID = sqlite_last_insert_rowid($database);
for ($j = 0; $j < 3; $j++) {
for ($x = 0; $x < $lenght; $x++) {
$test1 .= rand(0, 9);
$test2 .= rand(0, 9);
}
$sql_2 = "INSERT INTO ex2 (ex1_ID, fname, lname) values ('$ex1_ID','$test1','$test2');";
$database->queryExec($sql_2);
}
}
I cant get the last ID from a ex1 table.
Please help!
UPDATED now that we have more information.
Since you use an object-model way to query your DB, did you try
$lastid = $database->lastInsertRowid();
?

Categories