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."')");
Related
I have an array in variable $id = Array([0] => 5 , [1]=> 6). Now I want to pass the value to the SQL query and calculate the SUM, but somehow it's not calculating the SUM rather then its displaying output 100500 which should be 600 (like: 100+500 = 600).
My PHP code is :
$id = $_POST['id'];
for($i = 0; $i<count($id); $i++) {
$sql = getAmount($id[$i]);
}
function getAmount(&$id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT SUM(amount) AS total FROM work WHERE id = (?)");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
$stmt->fetch();
echo $amount['total'];
}
You are not summing the sql result;
$id = $_POST['id'];
$sum = 0;
for($i = 0; $i<count($id); $i++) {
$sum = $sum + getAmount($id[$i]);
}
echo $sum;//Print the summing result
function getAmount(&$id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT SUM(amount) AS total FROM work WHERE id = (?)");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
$stmt->fetch();
return $amount['total'];
}
You should return query sum result from getAmount function and you should sum the returning results in the loop. After completed the loop, you can print the sum result.
column amount must be some of integer or float types: int, bigint, tinyint, longint, float, double
I want to generate unique username for every user during registration based on his/her name, user can change it later. If user entered 'smith doe' as his name in registration form, the auto generated username should be 'smith', but if 'smith' is already someone's username(u_name) then it should add any available number at the end of 'smith' : like- 'smith1' or 'smith2' or 'smith3' and so on...
Here is what i have tried :
$usnm = $_POST['name'];
$first_nut = explode(' ', $usnm);
$usnm3 = $first_nut[0];
$usnm5 = $usnm3;
function generateUsername($usnm3,$iteration = 0)
{
$generated = $iteration > 0 ? ($usnm3 . $iteration) : $usnm3; //Increment username
$query_usnm = mysqli_query($con, "SELECT * FROM user WHERE (u_name = '$generated' or u_name = '$usnm3') ");
if(mysqli_num_rows($query_usnm) > 0)
{
return generateUsername($usnm3,$iteration + 1);
}
return $generated;
}
$usnm4 = generateUsername($usnm5);
$sql = mysqli_query($con, "insert into user (name, u_name) values ('$name', '$usnm4');");
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 :)
I would like to post the id of the evenement table into the evenementontvanger.idEvent column. I tried to use the mysql_insert_id() but this doesnt work. ill tried it like this:
<?php
//include db configuration file
include 'connection.php';
function user_joined($user_werknemer,$user_project,$user_klant,$user_taak,$user_name,$user_desc, $user_start, $user_startdate, $user_starttime, $user_end, $user_enddate, $user_endtime, $user_color){
$q = "INSERT INTO evenement (id,title,description,start,startdate,starttime,end,enddate,endtime,color) VALUES
('','".$user_name."','".$user_desc."','".$user_start."','".$user_startdate."','".$user_starttime."','".$user_end."','".$user_enddate."','".$user_endtime."','".$user_color."') ";
$qo = "INSERT INTO evenementontvanger (idWerknemer,idProject,idEvent,idKlant,idTaak) VALUES ('".$user_werknemer."','".$user_project."','','".$user_klant."','".$user_taak."')";
mysql_query($q);
$id = mysql_insert_id();
$query = 'INSERT INTO evenementontvanger("idEvent") VALUES('.$id.')';
mysql_query($qo);}
if(isset($_POST['user_werknemer'],$_POST['user_project'],$_POST['user_klant'],$_POST['user_taak'],$_POST['user_name'],$_POST['user_desc'],$_POST['user_startdate'],$_POST['user_start'],$_POST['user_starttime'],$_POST['user_enddate'],$_POST['user_endtime'],$_POST['user_end'],$_POST['user_color'],$_POST['action'])){
$user_werknemer=$_POST['user_werknemer'];
$user_color=$_POST['user_color'];
$user_name=$_POST['user_name'];
$user_desc=$_POST['user_desc'];
$user_project=$_POST['user_project'];
$user_klant=$_POST['user_klant'];
$user_taak=$_POST['user_taak'];
$user_start=$_POST['user_startdate']." ".$_POST['user_starttime'];
$user_startdate=$_POST['user_startdate'];
$user_starttime=$_POST['user_starttime'];
$user_end=$_POST['user_enddate']." ".$_POST['user_endtime'];
$user_enddate=$_POST['user_enddate'];
$user_endtime=$_POST['user_endtime'];
$action=$_POST['action'];
if ($action=='joined'){
user_joined( $user_werknemer, $user_project, $user_klant, $user_taak, $user_name, $user_desc, $user_start, $user_startdate, $user_starttime, $user_end, $user_enddate, $user_endtime, $user_color);
}
}
/*if ( (isset($_POST["id"]) && strlen($_POST["id"]) >= 3 && strlen($_POST["id"]) <= 60) &&
(isset($_POST["name"]) && strlen($_POST["name"]) >= 3 && strlen($_POST["name"]) <= 50) &&
(isset($_POST["age"]) && strlen($_POST["age"]) >= 3 && strlen($_POST["age"]) <= 40) )
{ //check $_POST["name"] and $_POST["address"] and $_POST["city"] are not empty
$id = $_POST["id"];
$name = $_POST["name"];
$age = $_POST["age"];
$q = "INSERT INTO tbltest ( id, name, age) VALUES
('".$id."','".$name."','".$age."')";
mysql_query($q);
}*/
?>
I also tried to work with last_insert_id. But this doesnt put the id in the idEvent too.
In the following query,
$qo = "INSERT INTO evenementontvanger
(idWerknemer,idProject,idEvent,idKlant,idTaak)
VALUES
('".$user_werknemer."', '".$user_project."',
'', '".$user_klant."', '".$user_taak."')";
You are setting an empty string '' from field idEvent.
You can directly use the LAST_INSERT_ID() in place of it, which is generated after executing the query defined for $q;
Like:
$qo = "INSERT INTO evenementontvanger
(idWerknemer,idProject,idEvent,idKlant,idTaak)
VALUES
('".$user_werknemer."', '".$user_project."',
LAST_INSERT_ID(), '".$user_klant."', '".$user_taak."')";
After executing mysql_query($q);,
Following statements are not necessary.
$id = mysql_insert_id();
$query = 'INSERT INTO evenementontvanger("idEvent") VALUES('.$id.')';
try to echo $id = mysql_insert_id();
if you have $id value or not or check with empty()
try replace
$query = 'INSERT INTO evenementontvanger("idEvent") VALUES('.$id.')';
to
$query = "INSERT INTO evenementontvanger(idEvent) VALUES('".$id."')";
Following is my code. The first part works perfectly, but the second loop is not producing any results. What this is doing is that it looks for the timetable, then takes out the classes in that, copies all the that and makes a new timtable with same data but a different name.
The other for loop is to add students into the classes of the time table. Ca some one be kind enough and help me out in this as I have been hitting my head on the wall for it now for 5 days.
Thank you in advance. The code:
<?php
$Q = "INSERT INTO time_table(name, term, year) VALUES
('".$name."', '".$term."', '".$year."')";
$res = $db->query($Q);
//for generating the max table id
$sql2 = "select MAX(table_id) as table_id
from time_table
";
$res2 = $db->query($sql2);
$count2 = $res2->num_rows;
$row2 = $res2->fetch_assoc();
$table_id = $row2['table_id'];
$Q = "SELECT class_id as tcid, day as d, teacher_id as tei, location as l
FROM class_time_table
WHERE term='".$copy."'";
$res = $db->query($Q);
$num_results = $res->num_rows;
for ($i = 0; $i <$num_results; $i++) {
$row = $res->fetch_assoc();
$Q4 = "SELECT * FROM students_class WHERE class_id = '".$row['tcid']."' and term = '".$copy."'";
$res4 = $db->query($Q4);
$row2 = $res4->fetch_assoc();
//for generating the max table id
$class_sysq = "select MAX(class_sys_id) as class_sys_id
from students_class
";
$class_sysr = $db->query($class_sysq);
$count_class_sys = $class_sysr->num_rows;
$class_row = $class_sysr->fetch_assoc();
$class_sys_idf = $class_row['class_sys_id']+1;
$Q5 = "INSERT INTO students_class (class_sys_id, teachers_id, location, max_students, class_term_fee, class_name, class_sub_name, term, year) VALUES ('".$class_sys_idf."', '".$row2['teachers_id']."', '".$row2['location']."', '".$row2['max_students']."', '".$row2['class_term_fee']."', '".$row2['class_name']."', '".$row2['class_sub_name']."', '".$term."', '".$year."')";
$res5 = $db->query($Q5);
//for generating the max table id
$max_c_id = "select MAX(class_id) as ci
from students_class
";
$r_mci = $db->query($max_c_id);
$count_class_sys = $r_mci->num_rows;
$mci_row = $r_mci->fetch_assoc();
$max_c_idf = $mci_row['ci'];
$query2 = "INSERT INTO class_time_table(class_id, teacher_id, table_id, location, day, term, year) VALUES
('".$max_c_idf."', '".$row['tei']."', '".$table_id."', '".$row['l']."', '".$row['d']."', '".$term."', '".$year."')";
$result2 = $db->query($query2);
$student_q = "SELECT students.first_name as fn, students.last_name as ln, students.email as e, students.mobile_phone as mp, students.home_phone as hp, students.gender as g, students.dob as dob, students.term_fee as tf, students.join_date as jd, students.date_added as da, student_attending_class.class_id as ci FROM students, student_attending_class, class_time_table where students.student_sys_id = student_attending_class.student_id and student_attending_class.class_id = class_time_table.class_id and class_time_table.class_id = '".$row['tcid']."'";
$student_res = $db->query($student_q);
$student_num_results = $student_res->num_rows;
for ($i = 0; $i < $student_num_results; $i++) {
$theRow = $student_res->fetch_assoc();
//for generating the new system id
$sql3 = "select MAX(student_sys_id) as ssi
from students";
$res3 = $db->query($sql3);
$count3 = $res3->num_rows;
$row8 = $res3->fetch_assoc();
$student_system_num = $row8['ssi']+1;
$query10 = "INSERT INTO students(student_sys_id, first_name, last_name, email, mobile_phone, home_phone, gender, dob, fee_due, registration_fee, term_fee, fee_paid, join_date, date_added) VALUES
('".$student_system_num."', '".$theRow['fn']."', '".$theRow['ln']."', '".$theRow['e']."', '".$theRow['mp']."', '".$theRow['hp']."', '".$theRow['g']."', '".$theRow['dob']."', '".$theRow['tf']."', 0, '".$theRow['tf']."', 0, '".$theRow['jd']."', '".$theRow['da']."')";
$result10 = $db->query($query10);
$query11 = "INSERT INTO student_attending_class(class_id, student_id, waiting_list) VALUES ('".$max_c_idf."', '".$student_system_num."', '0')";
$result11 = $db->query($query11);
}
}
?>
Don't use $i in the second loop but $n for instance.
i m not sure but you used same variable $i in both loop so maybe because of that your second loop not working. try another variable $j in second loop.
The code is poorly formatted, so it's easy to miss that you're using the same variable for both loops, hence when the second loop begins, the first loses track of its progress. Use foreach(), or a different variable name for the second loop.
You are probably getting a timeout due to having nested loops which both use the same variable, $i and it just keeps incrementing.
Try changing the second loop like so:
for($j = 0; $j < $student_num_results; $j++){
...
}