1

I am making a car dealership booking form and I need to select a staff member at random to go on the test drive

I've tried mt_rand() but I think I'm putting it in the wrong place

````````````````````````````````````
$sql = "INSERT INTO bookingcars (BookingStart, BookingEnd, BookingDate, MemberReference, ActivityID staffID) VALUES ('$timeStart', '$timeEnd', '$startDate', '$memberReference', '$activity', '$mt_rand(1, 4)staffID'";
````````````````````````````````````
  • This 'error' (of not-as-expected string interpolation) would be entirely avoided by using placeholders because the rand-generation expressions would be pulled out of the string interpolation. It would also eliminate SQL injection. See https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php for how to safely/correctly write basic database queries. – user2864740 May 05 '19 at 21:36
  • Can you clarify a couple of points: is the staff member an existing staff member with a staffID you can lookup from another table? what SQL platform are you working with? – strongbutgood May 05 '19 at 22:51

2 Answers2

0

while you could build it in the query, its little cleaner and easier to debug if you do something like:

$staff=rand(1,4).'staffID'; // assume you wanted 1staffID .. ?

//or did you just want $staff=rand(1,4);

$sql = "INSERT INTO bookingcars (BookingStart, BookingEnd, BookingDate, MemberReference, ActivityID, staffID) VALUES ('$timeStart', '$timeEnd', '$startDate', '$memberReference', '$activity', '$staff')";
  • I would recommend using `sprintf` for string concatenation. Writing code like that is bad habit – Tomasz Ferfecki May 05 '19 at 21:26
  • $memberReference = $_POST["memberReference"]; $activity =$_POST["Activity"]; $staff = $_POST[rand(1,4)."staffID"]; I've put it in like this but I get this error; Notice: Undefined index: 3staffID in E:\users\p012397i\webpages\Final Assignment\form\form.php on line 18 error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'staffID) VALUES ('10:00:00', '11:00:00', '2019-05-10', '3', '2', ''' at line 1 – Ollie Parrish May 05 '19 at 21:27
  • missing comma here `ActivityID staffID` in the query. but im not sure about the post code, you seem to be changing the question –  May 05 '19 at 21:30
  • @walkingRed That **actual** "bad habit" is writing code in that allows SQL Injection. sprintf won't fix that. – user2864740 May 05 '19 at 21:35
  • @user2864740 sure it is – Tomasz Ferfecki May 05 '19 at 21:36
0

Another way would be in your query values to add a subquery like ,...) VALUES (..., (SELECT DISTINCT (Id) FROM stalesstafftable order by Rand() limit 1))

imposterSyndrome
  • 896
  • 1
  • 7
  • 18