basic PHP & SQL question thread - help a newb

Turbonium

Platinum Member
Mar 15, 2003
2,109
48
91
Can you not declare a variable to be global while assigning it a value in the same statement?

PHP:
<?php
function outputMethod() {
	global $varInt=10;
	global $intAdd=$varInt*2;
}

outputMethod();
echo $intAdd;
?>

Nothing is outputted (it's supposed to output 20) unless I change it to the following:

PHP:
<?php
function outputMethod() {
	global $varInt,$intAdd;
	$varInt=10;
	$intAdd=$varInt*2;
}

outputMethod();
echo $intAdd;
?>
 
Last edited:

Turbonium

Platinum Member
Mar 15, 2003
2,109
48
91
Can you not do the following?

Code:
$var=5;

echo "<br>" + $var;

And expect the following to be parsed?:

Code:
<br>5

Which would produce the following output?:

Code:
5

So far, I can only produce the above output by doing the following:

Code:
$var=5;

echo "<br>";
echo $var;
 
Last edited:

Cerb

Elite Member
Aug 26, 2000
17,484
33
86
If you are going to modify a value like that, keep as much local as possible, and pass values.
Code:
function outputMethod($dbl_this) {
    return $dbl_this*2
}
$varInt = 10;
echo outputMethod($varInt);
Also, you need to tell it to return something for it to return a value. PHP functions are subroutines quite capable of returning nothing.

http://php.net/manual/en/language.operators.string.php

PHP has a special concatenation operator.
 

Turbonium

Platinum Member
Mar 15, 2003
2,109
48
91
See, I just discovered that you can actually echo a function, such as with:

PHP:
echo strlen(stringHere) {
}

I'm assuming echoing a function returns the output of the function, whatever that may be (string, integer, or whatever) as a string.

I still don't understand why it doesn't work in the 1st case though. If I'm declaring something as global, it means it should be available outside of its function, right? So how are the two ways of coding that any different? One is just shorthand form as far as I can tell. I mean, I should even be able to do this:

PHP:
<?php
function outputMethod() {
	global $varInt=10,$intAdd=$varInt*2;
}

outputMethod();
echo $intAdd;
?>

Ignore efficiency and good programming practices here. I'm just trying to understand why the code, syntactically or logically, doesn't work in the original question, or in the code block shown above.
 
Last edited:

Cerb

Elite Member
Aug 26, 2000
17,484
33
86
See, I just discovered that you can actually echo a function
Last I knew, no, you could not. You can echo a value that can be automatically converted into a string. You are not echoing the function, but the value it returns.
Code:
echo myfunc($var);
Is identical to:
Code:
$var_myfunced = myfunc($var);
echo $var_myfunced;

I still don't understand why it doesn't work in the 1st case though. If I'm declaring something as global, it means it should be available outside of its function, right?
Yes, but it aught to already exist. Declaring a variable in a wider scope from a function would be such a bad practice I can honestly say that I've never seen it done. You're probably dealing with stuff in PHP that's probably only tested in so far as making sure it doesn't crash the interpreter :). It probably would work if the variables actually existed in a wider scope, already.

Code:
$myvar = 10; // REALLY important part

function dostufftovar() {
    global $myvar;
    return $myvar*2;
}

echo dostufftovar();
The above is the way it should be done, if you're planning on using a global variable. For simple things like adjusting numbers, doing it that way is just plain wrong. However, it can be helpful when the alternative is passing many variable arguments to functions, when they are going to be the same for any given page being processed (such as config tables and DB connections).

So how are the two ways of coding that any different?
One names, binds, and modifies a variable that does not exist in its own scope, making the act of doing so a kind of programmer voodoo. One has a function return a value, which is about as common and straight-forward as it gets.
Code:
// y = f(x)
// Compare with:
echo strlen(mystring);

Also, the following gives me a syntax error (even if filled in with code, and closed with a semicolon), having decided to check it out, given how weird it looked.
Code:
echo strlen(stringHere) {
}
 
Last edited:

Turbonium

Platinum Member
Mar 15, 2003
2,109
48
91
Guess I didn't quite understand the tutorial and what it was trying to say. I thought you have to state a variable as being global when it is declared within a function for that variable to be available outside of that function.

I'm by no means a programmer by nature. I just tend to plow through whatever needs to be done and I make it work in the end. That being said, my most complete program ever (a Java game) is over 1000 lines of mostly if/else statements, nested or otherwise. Not efficient, but it works. I mean, I never quite used methods for collision detection in it, but used comparisons (if/else statements) for collision detection instead, which made for very difficult and slow coding. I also couldn't add more levels and obstacles on the fly, but had statements for literally each object. So inefficient.

I'm soon going to find out if programming properly is too abstract for me or not. I'm hoping it isn't.
 
Last edited:

Turbonium

Platinum Member
Mar 15, 2003
2,109
48
91
Code:
$myvar = 10; // REALLY important part

function dostufftovar() {
    global $myvar;
    return $myvar*2;
}

echo dostufftovar();
This is weird. I mean, I could do it that way, but that's just not how my mind works (at the moment anyway). I do it like this:

PHP:
<?php
$varInt=10;
$intAdd;

function outputMethod() {
	global $varInt, $intAdd; //Tells the function to fetch the given variables from outside itself
	$intAdd = ($varInt*4)+2;
}

outputMethod(); //Runs the function once, updating variable values accordingly (if applicable)
echo $intAdd;
?>

At least in this case, it makes no difference, because the method/function (same thing, right?) is not one that is going to be re-used; rather, I'm using it just to see if my syntax is correct. I can see a return value being useful in cases of re-use, though. Or am I wrong? Maybe I'm just not getting it at the most basic level.

</newb>
 
Last edited:

Cerb

Elite Member
Aug 26, 2000
17,484
33
86
At least in this case, it makes no difference, because the method/function (same thing, right?)
No. A method is specifically a named recipient for a message, in an object. They work the same, but technically, methods only exist within objects, in an OOP programming language; and outside of OOP, do not exist at all.

is not one that is going to be re-used; rather, I'm using it just to see if my syntax is correct. I can see a return value being useful in cases of re-use, though. Or am I wrong?
Yes and no. Passing and returning also has an advantage of voluntarily enforcing discipline in terms of variable manipulation. But, that's one of the more subtle uses. More commonly, if there's no reuse, it's primarily done for readability, so that the main logic code isn't stuffed full of a bunch of code that isn't handling that logic.

In such a simple case, with no re-use, the best thing to do is just not even use a function. Simply modify the variables right there in the same code block as the echo.
 

Turbonium

Platinum Member
Mar 15, 2003
2,109
48
91
No. A method is specifically a named recipient for a message, in an object. They work the same, but technically, methods only exist within objects, in an OOP programming language; and outside of OOP, do not exist at all.

Yes and no. Passing and returning also has an advantage of voluntarily enforcing discipline in terms of variable manipulation. But, that's one of the more subtle uses. More commonly, if there's no reuse, it's primarily done for readability, so that the main logic code isn't stuffed full of a bunch of code that isn't handling that logic.

In such a simple case, with no re-use, the best thing to do is just not even use a function. Simply modify the variables right there in the same code block as the echo.
Thanks.

Speaking of OOP: I never quite understood the concepts of it, in terms of the abstract stuff (I'm not sure I really get the difference between OOP and non-OOP languages), but I learned how to use the syntax and rules to make the computer do what I wanted it to do.

Is that a bad sign? I mean, I want to be competent at this stuff. I've just never been the super nerdy type though that thinks abstractly with ease (I'm sort of in between "average person" and "programmer" in terms of my thought process, meaning if I try hard enough, it gets done, but it's a lot of work).
 

Cerb

Elite Member
Aug 26, 2000
17,484
33
86
I'm by no means a programmer by nature. I just tend to plow through whatever needs to be done and I make it work in the end.
That's mostly what programmers do. There just happens to be decades of development of tools and methodologies to get that done better, both in terms of computers themselves, programming languages, and thought patterns. It's not like any of it was just pulled out of thin air (well, maybe COBOL, and other early, "business languages" :)).

That being said, my most complete program ever (a Java game) is over 1000 lines of mostly if/else statements, nested or otherwise. Not efficient, but it works. I mean, I never quite used methods for collision detection in it, but used comparisons (if/else statements) for collision detection instead, which made for very difficult and slow coding. I also couldn't add more levels and obstacles on the fly, but had statements for literally each object. So inefficient.
That's what focusing on data structures (objects), and functions, is meant to deal with. Make a type for each type of data structure, make functions to work on it, so that each unique state change has a related function. You can then combine functions, add new functions, extend the data structure for new features, etc..

Prior to Algol, how you were doing it was basically it. Languages which learned from Algol 60 and LISP added more and more stuff to make things better (better, in this case, in a many-dimensional thing, and no one way or feature set is best, once you get to isolating work inside procedures that can effectively nest code). You've got to catch up on the last 50 years of programming advancements :).

OOP is one of several useful paradigms that work, and generally a fairly good one, but not the only one or best one, necessarily. The most important thing is to think about modularity. In more normal terms: divide and conquer. Each thing has certain activities which may be performed on it. Define and implement those, with as little dependency on the whole project as possible. OOP may be a good way to go about it, but it's just a tool. The act of organizing what you have and what gets done to it is fundamental, and can be done in non-OOP PHP just as well as anything OOP (including OOP PHP :)).

http://objc.toodarkpark.net/oop.html#893
Skimming it over, this looked like a really good explanation, with none of the taint of thinking that modern COBOLs like Java.

An OOP language supports data structures with defined procedures (methods) that work on the data in the structure, and are treated as part of the structure itself. The implementation of the data storage itself, and those methods, is hidden from the users of it. It is entirely a means of providing useful abstractions, compared to globally exposing the organization of the data structures, so that many users of them will need to be modified if any changes are made (you can expose implementation in OOP, but you can't hide it as easily with most other paradigms). In an OOP language, every unique object type gets to be its own API specification.
 
Last edited:

Turbonium

Platinum Member
Mar 15, 2003
2,109
48
91
If I understand everything you said in the above post within 6 months, I will consider that a success.
 

sourceninja

Diamond Member
Mar 8, 2005
8,805
65
91
Can you not do the following?

Code:
$var=5;

echo "<br>" + $var;

And expect the following to be parsed?:

Code:
<br>5

Which would produce the following output?:

Code:
5

So far, I can only produce the above output by doing the following:

Code:
$var=5;

echo "<br>";
echo $var;

You need to use the . when concatenating in php (I know it's strange). So it would be
Code:
$var = 5
echo '<br />' . $var;
 

Cerb

Elite Member
Aug 26, 2000
17,484
33
86
OK, so backing WAY up, you already noted that just doing a simple iterative program was slow/inefficient to develop**

Instead of looking at the program as, "I need to do this, then do this, then do this," think, "I need to break this big problem down into smaller problems, and make it by building it by solving the small problems first**"

Java and PHP support objects (Java requiring them, PHP having added OOP), so you'd tend to use objects** But you can use an array just as well as an object** That's an implementation detail**

The thing to do is look at all the global variables you're probably using now, and things you couldn't add, and try to encapsulate them as their own whole entities** For instance, you might have a level as a data structure** It would then have references to things contained in the level (a player, a monsters list, an item list, etc**)** If it were set up with a simple grid, you might have that grid and what's on it in that data structure (so you'd then need to define the grid's tiles, too)**

So, then, you can have say, a monster** It needs a position in the level, possible moves per time/turn, possible actions when the player gets near, some way to track health status, etc**** You could then look at that, and realize that any 'actor' on a level needs those same things, so add a hostility flag to make it a monster, or even go further and add a faction tag**

Now, defining what those entities can do would make up functions for them (or methods in their objects, with OOP--same thing, different organization)** The data structure itself for each thing represents its state** The functions change that state**

So, then, after following that out further, the main engine of the game will call those functions to change those states, rather than directly manipulating the state data** There are many benefits, but the biggest benefits to a small one-man project will be that of simpler, easier-to-follow code, and the ability to move code around to where it needs to be called, which may very well change as features get added or removed.

Code:
actor_attack($monster["imp21"], $player)
Instead of:
Code:
$attack = $imp21_attack * rand(0, 100);

if ($attack > $player_dodge) {
    $damage = rand($imp21_damage_min, $imp21_damage_max)
              * (1.0-$player_armor);
    if ($player_health > $damage) {
        $player_health -= $damage;
        // other related code
    } else {
        // game over code
    }
} else {
    // miss code
}

So, let's say every critter, and the player, is a simple old table (PHP array), like so:
Code:
actor = {
    "health" => num > 0 iff not dead,
    "attack" => num > 0,
    "dodge" => num > 0 <= 100,
    "defense" => num > 0 <= 1 (1 == immortal?),
    "dmg_min" => num >= 0,
    "dmg_max" => num >= dmg_min,
    "x" => valid grid column,
    "y" => valid grid row
}
The attack function might look like (note: I'm rusty on PHP, so this may be syntactically incorrect):
Code:
function actor_attack($attacker, $defender) {

    if ($attacker["attack"] * rand(0, 100) > $defender["dodge"]) {
        $dmg_dealt = rand($attacker["dmg_min"], $attacker["dmg_max"])
                     * (1.0 - $defender["defense"]);

        if ($defender["health"] > $dmg_dealt) {
            $defender["health"] -= $dmg_health;
            event["was_hit"]($attacker, $defender, $dmg_dealt);

        } else {
            event["was_killed"]($attacker, $defender, $dmg_dealt);
        }
    } else {
        // miss code, if any
        event["was_not_hit"]($attacker, $defender);
    }
}
I can assume that the functions in the event array will handle the special work not in this function, and pass it off to them, giving them just enough local info to get by with. They can then be made into simple dummy functions until fleshed out. The attack/defend code also doesn't have to have any overlap with movement, reach, turns, or anything else, either--it can be called wherever it is needed, which could very well change over time. So, much of the program can be changed without affecting it. It's a nice little modular chunk of the much bigger system. So now, there's an attack+hit/miss function that will work with an arbitrary number of game entities, using event-driven coroutine equivalents (event["name"](args) can call further events, until the turn is over, FI), and no fancy uber-abstract OOP for miles.

The thing is, building up like that, the rest of it can wait, and doesn't yet matter. Design, build, and test the small parts first, on their own, then make the larger parts with them.
 
Last edited:

Turbonium

Platinum Member
Mar 15, 2003
2,109
48
91
Ok, so I'm working on trying to understand some basic SQL, and I'm just wondering: where exactly do you "script" the SQL stuff? For example, commands like:

Code:
CREATE DATABASE database_name

Are you supposed to make a .txt file or something which you then access from within a certain .php page? I'm so lost, lol. Being in my late 20s doesn't make things easier on the learning side.
 

Cerb

Elite Member
Aug 26, 2000
17,484
33
86
The DBMS has an interactive interpreter, and all SQL it receives is treated the same as if it were typed into that. So you can run mysql -u username, get a prompt, and type it in (assuming MySQL). Or, have it all in a file, or just as strings in your program.

Or, you have that hidden for this stuff, with a front end. I think MySQL Workbench is what you'd be looking for for MySQL.
 

Ken g6

Programming Moderator, Elite Member
Moderator
Dec 11, 1999
16,252
3,848
75
That appears to depend strongly on the database you're using, and weakly on the PHP libraries you're using. For instance, Drupal has a drupal_query function. If you're just using MySQL, you want "mysql_query".

Further, you generally want to create the database before running PHP against it. There are usually command-line interfaces to databases, as well as GUIs. My slightly quirky preference is for Squirrel SQL.
 

trexpesto

Golden Member
Jun 3, 2004
1,237
0
0
Bro, long ago I had the same inclination/requirement to dive in, and have found it's worth its weight in exponents to have a learning track separate from the implementing track in my life.
Once a very good programmer saw a book on my shelf at work and said, "See, you use that more like a reference than a tutorial," and I was like *SMACK* yeah you got me. It's part of struggling to get up to speed, but not the best position in which to be.
 
Last edited:

Turbonium

Platinum Member
Mar 15, 2003
2,109
48
91
Bro, long ago I had the same inclination/requirement to dive in, and have found it's worth its weight in exponents to have a learning track separate from the implementing track in my life.
Once a very good programmer saw a book on my shelf at work and said, "See, you use that more like a reference than a tutorial," and I was like *SMACK* yeah you got me. It's part of struggling to get up to speed, but not the best position in which to be.
Well what do you suggest I do?

Honestly, does anyone recommend taking any university-level classes for this kind of stuff? Or is it just a waste of money?

I don't even know if I want to do this for a living, but if I could do it for a living, I probably would, given I'm not too fond of my chosen career path (which has nothing to do with computers).
 

Cerb

Elite Member
Aug 26, 2000
17,484
33
86
One thing you could always do is try checking out videos of lectures, like these, these, or these.

Whether a uni level course would do any good would very much depend on the quality of the course, as they are not remotely uniform.

P.S. http://www.saylor.org/majors/computer-science/ -- no experience or anything, it just kind of popped up while I was looking for the old MIT lectures, and looks interesting (I thought I'd bookmarked them, but hadn't).
 
Last edited:

sourceninja

Diamond Member
Mar 8, 2005
8,805
65
91
That appears to depend strongly on the database you're using, and weakly on the PHP libraries you're using. For instance, Drupal has a drupal_query function. If you're just using MySQL, you want "mysql_query".

Further, you generally want to create the database before running PHP against it. There are usually command-line interfaces to databases, as well as GUIs. My slightly quirky preference is for Squirrel SQL.

Actually, it is my opinion (and I'm not alone) that you should never anything when writing php except for PDO (or the other alternatives). That way, if you have to change databases in the future (or support multiple databases) you can easily accomplish this. Further more, it's no different or more difficult when compared to using the native DB functions.

Compare

Code:
$pdo = new PDO("mysql:host=localhost;dbname=database", 'username', 'password');
$sql = 'SELECT * FROM users WHERE username = :username AND email = :email AND last_login > :last_login';
$params = array(':username' => 'test', ':email' => $mail, ':last_login' => time() - 3600);
$pdo->prepare($sql);
$pdo->execute($params);
To
Code:
$mysqli = new mysqli('localhost','username','password','database');
$sql = 'SELECT * FROM users WHERE username = ? AND email = ? AND last_login > ?';
$query = $mysqli->prepare($sql);
$query->bind_param('sss', 'test', $mail, time() - 3600);
$query->execute();
 

trexpesto

Golden Member
Jun 3, 2004
1,237
0
0
It's not easy to be a professional programmer, but I don't want to discourage you.
Strictness of method, clarity of vision, good communication, and continuous learning are some characteristics of a good programmer. A phlegmatic temperament helps.
Cultivate these as you go. To your advantage, it's normal to re-educate in the industry, so you can get the basics solid and then specialize in the hot new thing whatever that is.

PHP is a pretty arbitrary language, and there's usually a bunch of web stuff going on around it. Some others are more logical and transferable, and may be a better first language to establish concepts in a clear way. It is widely deployed as far as jobs - but that should not be your main consideration for learning. It is something where you get to see results quickly, and that inspires interest which is valuable.

w3 is not a good tutorial. Too disjointed. Find a holistic one.

Cerb's second link goes to Malan, my fave lecturer of all time. EdX has him now: CS50x is front and center on the home page: http://www.edx.org/ and here is his 2010 class "Building Dynamic Websites" http://cs75.tv/2010/fall/
Academicearth is another source of good video lectures.

How's craigslist look up there?
 
Last edited: