How to generate user id when submmiting form to database.

Discussion in 'PHP' started by Avinash Rai, Jul 19, 2013.

  1. #1
    Hi all,
    I have to submit form values in database and provide user with uid.however m trying this but getting error.please help me out.
    here is my code.
    insert.php

    <?php
    $con=mysqli_connect("localhost","aman","avin10889","my_db");
    // Check connection
    if (mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    function getUserId()
    {
    $result=mysqli_query("select max(uid) from persons");
    while($row=mysqli_fetch_array($result))
    {
    $usid=$row["max(uid)"];
     
    }
    //echo $usid;
    return $usid++;
     
    }
    $uid=getUserId()+1;
    //$etype=$_POST[''];
    //echo $uid;
    $fname=$_POST['fname'];
    $lname=$_POST['lname'];
     
    echo "<br>Your User id is::";
    echo $uid;
     
    echo "<br>";
    $test=mysqli_query("insert into register values('uid','$fname','$lname')");
     
    echo "<br />";
    echo "<U><b>Data Inserted Successfully<U><b><br><br>";
     
    mysqli_close($con);
    ?>
    PHP:
    form.php

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Home</title>
    </head>
     
    <body>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>
     
    <body>
    <form name="Registration" action="winsert.php" method="post" onsubmit="">
    <table width="953" border="0" cellspacing="0" cellpadding="0">
    <tr>
    <td height="10"></td>
    </tr>
    <tr>
    <td height="10"></td>
    </tr>
    <tr>
    <td height="10" ></td>
    </tr>
    <tr>
    <td align="left" valign="top">
    <table width="900" border="0" cellspacing="3" cellpadding="3">
    <tr>
    <td width="218" align="right"><span class="red">*</span> <span lang="en">First Name:</span></td>
    <td width="644"><input name="fname" type="text" class="text_box" value="" /> <br />
    </td>
    </tr>
    <tr>
    <td align="right"><span class="red">*</span><span lang="en">Last Name:</span> </td>
    <td><input name="lname" type="text" class="text_box" value=""/>
    </td>
     
    <tr>
    <td align="right">&nbsp;</td>
    <td><table width="304" border="0" align="left" cellpadding="0" cellspacing="0">
    <tr>
    <td width="138" align="left" valign="top"><input type="submit" name="sub" value="Get Registered" lang="en"/></td>
    <td width="315" align="left" valign="top"><a href="create_account.html" style="text-decoration:none"><input type="submit" name="Submit"value="Cancel" lang="en"/></a></td>
    </tr>
     
    </table></td>
    </tr>
    </table></td></tr>
    <tr>
    <td>&nbsp;</td>
    </tr>
    </table>
    </form>
    </body>
    </html>
     
    </body>
    </html>
    PHP:
    it shows error as:

    Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\winsert.php on line 10

    Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\winsert.php on line 11

    Notice: Undefined variable: usid in C:\xampp\htdocs\winsert.php on line 17

    Your User id is::1

    Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\winsert.php on line 31

    Data Inserted Successfully
     
    Last edited by a moderator: Jul 20, 2013
    Avinash Rai, Jul 19, 2013 IP
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    You're not passing the mysqli object and/or link to the object to the function, or the mysqli_ statements... That variable you made with _connect has to be passed to every function... Though that's why I don't think those stupid malfing functions should even exist and it should be object only -- like PDO is.

    MANUALLY trying to create user ID's is a horrifically bad idea. Since these scripts could run simultaneously in an unpredictable order, you could end up with multple users trying to set the SAME ID!!! When you made your table, the first field should be something like:

    CREATE TABLE users (
    	id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    	name VARCHAR(63),
    	passcrypt VARCHAR(128),
    	registered_date DATETIME,
    	last_access DATETIME
    )
    Code (markup):
    That way when you insert the user thus: (assumes $db is the connected mysqli object)
    $statement = $db->prepare('
    	INSERT INTO users (
    		name, passcrypt, registered_date, last_access
    	) values (
    		?, ?, NOW(), NOW()
    	)
    ');
    
    $statement->bindParam(
    	'ss',
    	$_POST['name'],
    	hash('sha256', $_POST['name'] . $_POST['password'])
    );
    	
    $statement->execute();
    
    Code (markup):
    The user ID is auto-generated. If you REALLY need that ID right then and there (for setting it in $_SESSION for example) you can use this:

    $id = $db->insert_id;
    Code (markup):
    AFTER the execute, which returns the most recently auto-generated ID on the connection from the last run INSERT. You could use $statement->insert_id, but if you run multiple executes off a single $db->prepare, you'll get the ID of the first execute, not any later ones... Generally it's just safer to use $db's copy instead.

    Basically, you seem to be trying to brute force something mysql can do for you automatically.

    Hope this helps.
     
    deathshadow, Jul 20, 2013 IP
    ekim941, Strider64 and ryan_uk like this.
  3. ekim941

    ekim941 Member

    Messages:
    74
    Likes Received:
    7
    Best Answers:
    7
    Trophy Points:
    33
    #3
    To solve your errors (as deathshadow suggested) use $con as the first parameter of your mysqli statements:
    mysqli_query($con, "Your query");
    PHP:
     
    ekim941, Jul 23, 2013 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #4
    Actually, I wouldn't suggest that, though that answer IS correct... I personally think the function based versions of mysqli should go the way of the dodo, just like mysql_ functions. Is it really so hard to do $db->command(params) instead of command($con,params) ?!?

    The OOP version just seems a lot cleaner to me -- but then I like that it's extensible, since I tend to override many of the default functions with my own for security reasons. (Though I do more in PDO than mysqli)
     
    deathshadow, Jul 23, 2013 IP
  5. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #5
    The userid really needs to be set to AUTO_INCREMENT, else it's just asking for trouble.

    Run this query once
    ALTER TABLE persons MODIFY uid INT AUTO_INCREMENT PRIMARY KEY
    Code (markup):
    Or if the primary key is already defined

    ALTER TABLE persons MODIFY uid INT AUTO_INCREMENT
    Code (markup):
    That will save you sooo much hassle.

    The PDO thing is a great idea too.
     
    blueparukia, Jul 23, 2013 IP
  6. ekim941

    ekim941 Member

    Messages:
    74
    Likes Received:
    7
    Best Answers:
    7
    Trophy Points:
    33
    #6
    Deathshadow, I'm surprised to hear you say that the OOP version seems cleaner. One of the biggest arguments against using OOP is that it produces bloated code which you don't seem to be a fan of.

    If the OP is only using php and MySQL to persist form data, I can't imagine that there would be any benefit to using OOP when procedural code would require fewer lines. However, I see that one piece of data being persisted is userid which makes me think that this is a small piece of a much larger project so you may be right in suggesting OOP.
     
    ekim941, Jul 24, 2013 IP
  7. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #7
    First, sorry folks if this treads slightly into threadjack territory, but Ekim941 did ask...

    That's one of those 'all or nothing' nonsensical claims I hear a lot... and in most cases it's pure BS used by people who can't wrap their heads around objects. (Just as some OOP programmers piss all over functional programming with a bunch of made up bull)

    For the most part it comes down to the language being used and how it implements them, as well as the task at hand.

    Objects do incur an under the hood penalty when initialized, but that penalty can be made up for by their versatility, and the security advantages of isolating scope.

    In the case of mysqli in PHP, the functional versions WRAP THE OBJECT VERSION... you can tell this because mysqli_connect is an ALIAS of mysqli::__construct -- they are the EXACT SAME THING returning a mysqli object as the result. You can use the functional connect and then use the object methods of accesss -- or you could do a 'new mysqli' and use the procedural versions by passing the result.

    Which means all those 'functions' are for all intents and purposes... well, let's use prepare as an example. Dimes to dollars under the hood it's the same as wasting time doing this:

    function mysqli_prepare($con,$queryString) {
      return $con->prepare($queryString);
    }
    Code (markup):
    Which is pretty ****tarded -- Though that's a guess -- if they have any brains at all they made it a language construct/alias instead of an actual function; but if they did so, that's still extra overhead for the parser when it's just using objects ANYWAYS, and simply hiding it for the dipshits who can't grasp objects. If nothing else, it's passing an extra reference to an object on the stack -- say hello to more memory use and more time consumed for nothing.

    So if under the hood there's no real difference, how about the code written by the user? Well that can be shot down almost instantly by simply comparing apples to apples thus:

    procedural - 267 bytes
    <?php
    $db = mysqli_connect('localhost', 'dbUser', 'dbPassword', 'dbName');
    
    if (!$db) die(
    	'MySQLi  Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()
    );
    
    echo 'MySQLi Connected: ', mysqli_get_host_info($db), '<br />';
    
    mysqli_close($db);
    ?>
    Code (markup):
    objects - 252 bytes
    <?php
    $db = new mysqli('localhost', 'dbUser', 'dbPassword', 'dbName');
    
    if ($db->connect_error) die(
    	'MySQLi Error (' . $db->connect_errno . ') ' . $db->connect_error
    );
    
    echo 'MySQLi Connected: ', $db->host_info, '<br />';
    
    $db->close();
    ?>
    Code (markup):
    So close as to make no never-mind... though the object version is in fact LESS code.

    To me since it's already an object REGARDLESS of what set of commands you are using, you might as well use the object... especially since for me at least it's cleaner/clearer to see what's being manipulated FIRST, then the command.

    Though that's also another reason I prefer PDO over mysqli, it doesn't waste time making aliases or wrappers for procedural equivalents... just to add to it's being capable of multiple SQL engines, ability to pass arrays to PDOStatement::execute, more useful FETCH methodologies, etc, etc.
     
    Last edited: Jul 25, 2013
    deathshadow, Jul 25, 2013 IP
  8. Avinash Rai

    Avinash Rai Greenhorn

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    21
    #8
    Thanks a lot :).....i Got it...............
     
    Avinash Rai, Jul 25, 2013 IP