0

Hi I'm new to PHP after using ASP.NET, which is completely different in a confusing way, lol.

I have a question, in ASP.NET I've made a static void which returns 1 result from the SQL via a statement, which really helped me to get easily data and print it. Example for query:

getSqlData("SELECT id FROM users WHERE name = 'george'"); //returns the query string result

Ok so I've tried to make something similar in PHP, but it doesn't work at all.

class Database {

    //My functions
    public static function s($selection, $sqlQuery) {

        $result = mysql_query($sqlQuery);
        while ($row = mysql_fetch_array($result)) {
            echo $row['' . $selection];
        }
    }
}

Database::s("id", "SELECT id FROM characters WHERE name = 'naveh'");

What am I doing wrong? Is it even possible? Can I make even a PHP function which only take the query as a parameter so I won't need 2 and print it?

Sorry for being such a noob, thank you for any assistance.

Rizban Ahmad
  • 139
  • 1
  • 13
  • 1
    please do not use `mysql` functions anymore as they are deprecated and pose serious security risks, at least use `mysqli` or even better, `PDO`. – Pevara Nov 24 '16 at 23:59
  • 1
    of course it won't work, there's no connection, and since you're just starting out, why not start with PDO instead – Kevin Nov 25 '16 at 00:02
  • Did you make a connection to the database? `mysql_connect()` – RiggsFolly Nov 25 '16 at 00:02
  • 1
    Every time you use [the `mysql_`](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) database extension in new code **[a Kitten is strangled somewhere in the world](http://2.bp.blogspot.com/-zCT6jizimfI/UjJ5UTb_BeI/AAAAAAAACgg/AS6XCd6aNdg/s1600/luna_getting_strangled.jpg)** it is deprecated and has been for years and is gone for ever in PHP7. If you are just learning PHP, spend your energies learning the `PDO` or `mysqli` database extensions. [Start here](http://php.net/manual/en/book.pdo.php) – RiggsFolly Nov 25 '16 at 00:02
  • 1
    I will check out the PDO and mysqli as you mention, thanks. –  Nov 25 '16 at 00:11

1 Answers1

0

Here's a simple example that should be enough for you to get started:

First of all you need to set your connection parameters:

<?php
$connection = mysqli_connect("localhost","userName","pwd","dbName");

Then check if your connection works:

if (mysqli_connect_errno())
{
    echo "Error connecting to MySQL: " . mysqli_connect_error();
}

Now you are ready to execute your queries, for example:

mysqli_query($connection,"SELECT * FROM USERS");

or

mysqli_query($connection,"INSERT INTO USERS (user_name, pwd, access_level) 
        VALUES ('root','phpdev2016',99)");

And finally close the connection:

mysqli_close($connection);
deChristo
  • 1,860
  • 2
  • 17
  • 29