1

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!

4
  • 8
    The mysql_* functions are deprecated as of PHP v5.5 and have been removed as of v7.0. They should not be used for new code and should be swapped out for mysqli or PDO equivalents as soon as possible. Commented Mar 31, 2017 at 13:38
  • 3
    Error messages are a wonderful thing. You really ought to be checking for them by using error functions and looking at your server error logs. Commented Mar 31, 2017 at 13:39
  • You need quotes around your pid so it knows it is a string. Commented Mar 31, 2017 at 13:50
  • mysql is deprecated. Please use mysqli extension instead. Commented Mar 31, 2017 at 14:24

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much!
use either PDO or mysqli not mysql_query
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.