Naveh Naveh - 1 year ago 59
MySQL Question

PHP Getting 1 result from MySQL

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.

Answer Source

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

First of all you need to set your connection parameters:

$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");


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

And finally close the connection: