Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 3 123 LastLast
Results 1 to 15 of 44
  1. #1
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts

    Keeping variable when clicking link

    This is the weirdest thing. When purchasing an item, I need to check the id in the table to extract the name, cost, etc.
    However when the item is clicked on and sent over to the buy function, it says "You purchased the for "
    Also I am posting the error log. Thanks

    PHP Code:
    <?php
    $blacksmithQ
    mysqli_query($CharNameDB"SELECT * FROM rod_blacksmith ORDER BY id");

           echo 
    "Take a look at my equipment below. Be careful and make sure you can use what you buy.<br /><br />";
           echo 
    '<table width="75%"><tr><td style="background: blue; text-align: center;"><h3>ITEM NAME</h3></td><td style="background: blue; text-align: center;"><b>TYPE</b></td><td style="background: blue; text-align: center;"><b>COST</b></td><td style="background: blue; text-align: center;"><b>CAN EQUIP</b></td><td style="background: blue; text-align: center;"><b>PURCHASE</b></td></tr>';
            while (
    $blacksmithrow mysqli_fetch_array($blacksmithQ)) {
            echo 
    "<tr><td style='background: black;'><h3><a href=\"blacksmith.php?rod=buy:".$blacksmithrow['id']."\">".$blacksmithrow["name"]."</a></h3></td><td style='background: black; text-align: center;'><b>".$blacksmithrow["type"]."</b></td><td style='background: black; text-align: center;'>".$blacksmithrow["cost"]."</td><td style='background: black; text-align: center;'><b><font color=green>Yes</font></b></td><td style='background: black; text-align: center;'><input type='submit' name='submit' value='Buy'></td></tr>";

          }
           echo 
    '</table>';


           
    ?>
            </div>
           <?php
           
           
    if (isset($_GET['rod']))
    {
        
    $rod explode(':'$_GET['rod']);

        switch(
    $rod[0])
        {

            case 
    'buy':
                
    buy();
            break;
            
                }

    }
           
           function 
    buy() {
             
    $id $_GET['id'];
              
    $getitem mysqli_query($CharNameDB"SELECT * FROM rod_blacksmith WHERE id='$id' LIMIT 1");
        
    $itemrow mysqli_fetch_array($getitem);
        
        echo 
    "You purchased the <b>".$itemrow['name']."</b> for <b>".$itemrow['cost']."</b>";
           }

    [24-May-2014 17:46:38 America/Denver] PHP Notice: Undefined index: id in /home1/newrodga/public_html/courtyard/blacksmith.php on line 43
    [24-May-2014 17:46:38 America/Denver] PHP Notice: Undefined variable: CharNameDB in /home1/newrodga/public_html/courtyard/blacksmith.php on line 44
    [24-May-2014 17:46:38 America/Denver] PHP Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /home1/newrodga/public_html/courtyard/blacksmith.php on line 44
    [24-May-2014 17:46:38 America/Denver] PHP Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /home1/newrodga/public_html/courtyard/blacksmith.php on line 45
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #2
    Senior Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    4,474
    Thanks
    63
    Thanked 537 Times in 524 Posts
    Quote Originally Posted by myfayt View Post
    This is the weirdest thing.
    There is nothing weird about it at all. You're just not seeing what you've not taken into account. For a start you really MUST learn to debug. We've had this conversation before. Secondly you must start trying to understand that error messages are useful and you've done right posting them here but they contain everything you needed to fix your problem: [24-May-2014 17:46:38 America/Denver] PHP Notice: Undefined index: id in /home1/newrodga/public_html/courtyard/blacksmith.php on line 43

    Lets look at this:

    Quote Originally Posted by myfayt View Post
    PHP Code:
            echo "<tr><td style='background: black;'><h3><a href=\"blacksmith.php?rod=buy:".$blacksmithrow['id']"; 
    So that link will look like (using 22 as an example id):

    blacksmith.php?rod=buy:22

    Now you're clearly aware of this because you've done this:
    Quote Originally Posted by myfayt View Post
    PHP Code:
          
           
    if (isset($_GET['rod']))
    {
        
    $rod explode(':'$_GET['rod']);

        switch(
    $rod[0])
        {

            case 
    'buy':
                
    buy();
            break;
            
                }


    You've exploded $_GET['rod'] to get an array of parts seperated by the : character. If your switch finds that $rod[0] = 'buy' you then call buy().

    What happens here then?

    Quote Originally Posted by myfayt View Post
    PHP Code:
           
           
    function buy() {
             
    $id $_GET['id'];
              
    $getitem mysqli_query($CharNameDB"SELECT * FROM rod_blacksmith WHERE id='$id' LIMIT 1"); 
    Why are you not again exploding $_GET['rod'] ?

    You do not have a key in your $_GET array called id (hence the undefined index error) because you passed the id as part of your rod value in the $_GET array.

    So, here is a very simple and quick fix:

    PHP Code:
          
           
    if (isset($_GET['rod']))
    {
        
    $rod explode(':'$_GET['rod']);

        switch(
    $rod[0])
        {

            case 
    'buy':
                
    buy($rod[1]);  //Note parameter
            
    break;
            
                }

    }
           function 
    buy($id) {//Note parameter
    //Deleted $id = ...
              
    $getitem mysqli_query($CharNameDB"SELECT * FROM rod_blacksmith WHERE id='$id' LIMIT 1"); 
    See, it was all there right in front of you.

    Also as a secondary issue, you've also got this error message:
    [24-May-2014 17:46:38 America/Denver] PHP Notice: Undefined variable: CharNameDB in /home1/newrodga/public_html/courtyard/blacksmith.php on line 44

    $getitem = mysqli_query($CharNameDB, "SELECT * FROM rod_blacksmith WHERE id='$id' LIMIT 1");

    That means that CharNameDB is not set to anything. I'm assuming this is your database link variable that you set elsewhere in your main script. That means that inside your function, it is out of scope so you either need to pass it as a parameter or make it global like this:


    PHP Code:
          
           
    if (isset($_GET['rod']))
    {
        
    $rod explode(':'$_GET['rod']);

        switch(
    $rod[0])
        {

            case 
    'buy':
                
    buy($rod[1], $CharNameDB);  //Note parameter
            
    break;
            
                }

    }
           function 
    buy($id$CharNameDB) {//Note parameter
    //Deleted $id = ...
              
    $getitem mysqli_query($CharNameDB"SELECT * FROM rod_blacksmith WHERE id='$id' LIMIT 1"); 
    OR like this:

    PHP Code:
          
           
    if (isset($_GET['rod']))
    {
        
    $rod explode(':'$_GET['rod']);

        switch(
    $rod[0])
        {

            case 
    'buy':
                
    buy($rod[1]);  //Note parameter
            
    break;
            
                }

    }
           function 
    buy($id) {//Note parameter
    global $CharNameDB;
    //Deleted $id = ...
              
    $getitem mysqli_query($CharNameDB"SELECT * FROM rod_blacksmith WHERE id='$id' LIMIT 1"); 
    Last edited by tangoforce; 05-25-2014 at 04:20 AM.
    I can't really think of anything to write here now...

  • #3
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    Makes sense, yes I am forgetting the second explode. I'll try that out.

    As for $CharNameDB yes it's the database link and I tried to make it global in the function buy() but it still didn't accept it.

    I'll make the changes and get back to you.
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #4
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    It's working! Thank you. So apparently with mysqli (which I am new at, I've always done mysql), I need to set the variable and DB connection in both the switch and the function parameter. Is that correct?
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #5
    Regular Coder
    Join Date
    Sep 2011
    Posts
    428
    Thanks
    18
    Thanked 26 Times in 26 Posts
    Just set the MySQLi handler to a variable and call it as global in the functions you need to use it.

  • #6
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    You mean the database connection? If so I did try it as a global and it didn't work, unless I have to set it in the file that contains the link first.
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #7
    Senior Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    4,474
    Thanks
    63
    Thanked 537 Times in 524 Posts
    Quote Originally Posted by myfayt View Post
    You mean the database connection? If so I did try it as a global and it didn't work, unless I have to set it in the file that contains the link first.
    I can only assume that you're setting up your mysqli connection inside a function?

    If so, this is what you need to do:

    PHP Code:
    //declare MYSQLI variable
    $MYSQLI '';

    function 
    open_db()
       {
       global 
    $MYSQLI//Notice this is now the global not local variable
       
    $MYSQLI mysqli_connect($host$username$passwd$dbname);
       }

    function 
    insert_db($Variable)
       {
       global 
    $MYSQLI//Notice this is now the global not local variable

       
    $Variable mysqli_real_escape_string($Variable);
       
    mysqli_query("insert into `my_table` (`something`) values ('$Variable')");
       }

    //Do your stuff
    open_db();

    //Do more stuff
    insert_db(); 
    Do you see what I've done there? - I've declared a $MYSQLI variable in the main code (as an empty string but this doesn't matter). Then in both the other functions declared it as a global so that it accesses the GLOBAL variable not a LOCAL variable (a local variable would be only available inside
    I can't really think of anything to write here now...

  • #8
    Senior Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    4,474
    Thanks
    63
    Thanked 537 Times in 524 Posts
    Quote Originally Posted by myfayt View Post
    It's working! Thank you. So apparently with mysqli (which I am new at, I've always done mysql), I need to set the variable and DB connection in both the switch and the function parameter. Is that correct?
    You don't need to set it in the switch, just the buy() function as a parameter OR make it as global as I've recently demonstrated.
    I can't really think of anything to write here now...

  • #9
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    No wonder it wasn't working in multiple scripts, because it must have been a local variable. This makes sense, I've seen open_db before, but seemed to have skipped it.

    I do have one question, for the
    mysqli_query("insert into `my_table` (`something`) values ('$Variable')");
    How would I put in the table and value when using this?
    insert_db();
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #10
    Senior Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    4,474
    Thanks
    63
    Thanked 537 Times in 524 Posts
    Quote Originally Posted by myfayt View Post
    I've seen open_db before, but seemed to have skipped it.

    How would I put in the table and value when using this?
    open_db() and insert_db() were simply demo functions that I wrote to show you how to use the global variable. If you've seen open_db elsewhere, then that is purely coincidence and you should not consider it something to learn - I simply wrote it as a demo function and gave it the name open_db off the top of my head. Likewise I didn't show any parameters in the function calls because I did not consider them important - I was simply trying to show you how the principle of global variables works.

    The same applies for insert_db(). I wrote it and gave it that name off the top of my head.

    If you wanted to pass values into it, then as I've shown you previously, you simply use parameters:

    PHP Code:
    insert_db($Variable); 
    Then in your function declaration:

    PHP Code:
    function insert_db($Something)
       {
       
    //Use $Something here in this function
       

    If you want to use a function with multiple parameters:

    PHP Code:
    insert_db($Something$Else);

    insert_db($Try$This)
       {
       
    //Use $Try and $This variables in this function
       

    Likewise you can also set a default value for a function parameter:

    PHP Code:
    insert_db($Try$This 'Out')
       {
       
    //Use $Try and $This variables in this function however $This has the default value of 'Out' if nothing is passed in the function call.
       

    You would then call that function like this:

    PHP Code:
    insert_db($Some$Value); //Note the second parameter will be the value of $Value instead of 'Out' 
    or

    PHP Code:
    insert_db($Some'string'); //Note the second parameter will be 'string' instead of 'Out' 
    or

    PHP Code:
    insert_db($This); //Note the missing second parameter - will be 'Out' inside the function 
    I can't really think of anything to write here now...

  • #11
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    This is the coding that someone else wrote:

    PHP Code:
    if (!function_exists(opendb))
    {
        function 
    opendb()
        { 
    // Open database connection.
            
    global $dbsettings;
            
    //include_once('config.php');
            
    extract($dbsettings);
            
    $link mysql_connect($server$user$pass) or die(mysql_error());
            
    mysql_select_db($name) or die(mysql_error());
            return 
    $link;
        }

    then call it like this

    PHP Code:
    $link opendb(); 
    this was the connection page below

    PHP Code:
    <?php // config.php :: Low-level app/database variables.

    $dbsettings = array(
            
    "server"        => "localhost",     // MySQL server name. (Default: localhost)
            
    "user"          => "....",              // MySQL username.
            
    "pass"          => ".....",              // MySQL password.
            
    "name"          => ".....",              // MySQL database name.
            
    "prefix"        => "mygame",            // Prefix for table names. (Default: mygame) - WARNING! Changing this may cause errors.
            
    "secretword"    => "boo");             // Secret word used when hashing information for cookies.

    ?>
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #12
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    opendb doesn't work. I am apparently doing something wrong. If I post coding and errors are you willing to help me? Thanks
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #13
    Regular Coder
    Join Date
    Sep 2011
    Posts
    428
    Thanks
    18
    Thanked 26 Times in 26 Posts
    Quote Originally Posted by myfayt View Post
    If I post coding and errors are you willing to help me? Thanks
    I'm not too sure on this, someone else correct me if I'm wrong, but I have a wild hypothetical guess that this is the entire point of this forum.


    Now with sarcasm aside, post it (removing sensitive data obviously) and we'll see what we can do.

  • #14
    Senior Coder
    Join Date
    Apr 2010
    Posts
    1,555
    Thanks
    75
    Thanked 105 Times in 104 Posts
    Well I know that Tango is getting really pissed off at me, so thought I'd ask.

    DB Connection file (CharNameDB.php)

    PHP Code:
     <?php

      
    function opendb()
        {
            
    $link mysqli_connect("localhost""xx""xx""xx") or die(mysqli_error());
            global 
    $link;

        }
      
    ?>
    login.php

    PHP Code:
    <?php // login.php :: Handles logins 

    session_start();


    if (isset(
    $_GET['rod'])) {

        if (
    $_GET['rod'] == 'login') { login(); }

        elseif (
    $_GET['rod'] == 'logout') { logout(); }

    }



    function 
    login() {



        include(
    'CharNameDB.php');
        global 
    $link;


        if (isset(
    $_POST['submit'])) {


           
    $query mysqli_query($link"SELECT * FROM rod_AllUsers WHERE username='{$_POST['username']}' LIMIT 1");

            if (
    mysqli_num_rows($query) != 1) { die("You have entered an invalid username or password. Please go back and try again."); }

            
    $row mysqli_fetch_array($query);
            

          
    $_SESSION["username"] = "".$_POST['username']."";

            
    header("Location: createchar/menu.php");



            die();



        }


        require(
    'index.php');


    }

    Error results

    PHP Code:
    Warningmysqli_query() expects parameter 1 to be mysqlinull given in /home1/newrodga/public_html/login.php on line 27
    Warning
    mysqli_num_rows() expects parameter 1 to be mysqli_resultnull given in /home1/newrodga/public_html/login.php on line 29
    You have entered an invalid username 
    or passwordPlease go back and try again
    Been a sign maker for 7 years. My business:
    American Made Signs

  • #15
    Senior Coder
    Join Date
    Feb 2011
    Location
    Your Monitor
    Posts
    4,474
    Thanks
    63
    Thanked 537 Times in 524 Posts
    Quote Originally Posted by myfayt View Post
    Well I know that Tango is getting really pissed off at me, so thought I'd ask.
    What I get pissed with is that you make no attempt to actually learn or study anything but seem to be quite happy putting sites together - presumably charging serious cash and then asking us to fix your issues for free. I've seen a lot of this over the years

    Quote Originally Posted by myfayt View Post
    PHP Code:
     <?php

      
    function opendb()
        {
            
    $link mysqli_connect("localhost""xx""xx""xx") or die(mysqli_error());
            global 
    $link//See note

        
    }
      
    ?>
    Why have you deliberately ignored my advice and code sample and then put your global line UNDER the line of coder that sets the variable? Luckily php is a two pass compiler so it probably won't make any difference but thats not the point, you've ignored my advice and now come back complaining of errors!

    Quote Originally Posted by myfayt View Post
    [PHP]
    login.php

    PHP Code:
    <?php // login.php :: Handles logins 

    session_start();


    if (isset(
    $_GET['rod'])) {

        if (
    $_GET['rod'] == 'login') { login(); }

        elseif (
    $_GET['rod'] == 'logout') { logout(); }

    }



    function 
    login() {



        include(
    'CharNameDB.php');
        global 
    $link;

    }
    You've put your global declaration in your function correctly here but again you've ignored my previous of declaring the $link in your main code OUTSIDE of the two functions that declare they're using the global variable.

    To put it bluntly, if you do not declare your variable in your main code, then when you declare you're using the global variable inside your functions, what variable is your function supposed to work with if it has not been declared and initialised?

    Let me make my previous code a bit simpler for you as it clearly didn't sink in the first time:

    PHP Code:

    //This is the GLOBAL variable that your functions will use - YOU MUST DECLARE / INITIALISE IT.
    $MYSQLI '';

    function 
    open_db()
       {
       global 
    $MYSQLI//Notice this is now using the global not local variable

       //Your code here
       
    }

    function 
    insert_db($Variable)
       {
       global 
    $MYSQLI//Notice this is now using the global not local variable

       //Your code here
       

    Do you see what I did? - I set $MYSQLI to an empty string in the MAIN CODE so that functions (also known as sub routines) can access it. If you do not declare it in the main code then it does not exist. If it does not exist, then your functions cannot access it when you declare the use of the global variable.
    I can't really think of anything to write here now...


  •  
    Page 1 of 3 123 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •