PartyGuy
PartyGuy

Reputation: 68

Get data from database with PHP

I have the following PHP code but it doesn't work:

<?php
$pid = "test123";
$conn = mysql_connect('localhost', 'user', 'password'); 
mysql_select_db('database'); 
$result = mysql_query('SELECT name FROM my_table WHERE
channel=$pid', $conn); 
$content = mysql_result($result, 0);
echo $content;
?>

I just get a blank page...

Can someone pls help me?! Thank's!

Upvotes: 1

Views: 113

Answers (2)

Adam Forbis
Adam Forbis

Reputation: 461

This is how I would do it, in mysql and PDO.

Mysql

/*In the deprecated mysql extension*/
$pid = "test123";
/*connecting*/
$conn = mysql_connect('localhost', 'user', 'password');
mysql_select_db('database');
/*If this comes from outside you need to escape it*/
$pid = mysql_real_escape_string($pid, $conn);

/*Putting backtick around columns that are reserved words*/
$result = mysql_query("SELECT `name` FROM my_table WHERE
            `channel`= '$pid'", $conn);
$content = mysql_result($result, 0);
echo $content;

PDO

/*In PDO*/
$pid = "test123";
$pdo = new PDO("mysql:host=localhost;dbname=database", 'user', 'password');
/*Putting backtick around columns that are reserved words*/
$query = "SELECT `name` FROM my_table WHERE
            `channel`= :pid";
$pdo_stmt = $pdo->prepare($query);
/*Prepared statements escape it for you*/
$pdo_stmt->bindValue(":pid", $pid);
$pdo_stmt->execute();

echo $pdo_stmt->fetchColumn();

Upvotes: 1

Victor Anuebunwa
Victor Anuebunwa

Reputation: 2903

First, you should run away from using mysql_* functions, use mysqli_* instead. That said, you should display the data, not the result object.

Example

while ($row = mysql_fetch_assoc($result)) {
      echo $row['column_name'];
}

Still doesn't work? Use mysql_error() to view the mysql error message.

Upvotes: 0

Related Questions