0

Sorry for this very beginner question... I have a table like

| id | block_1 | block_2|
-------------------------
| 1  | Mark    | John   |
| 2  | Antony  |        |
------------------------- 

i want check if text in a cell match my variable for example $name:

...
$sql = "SELECT * FROM my_table WHERE id='1'";
$res = mysql_query($sql, $connection);
$row = mysql_fetch_array($res);


$block1 = $row['block_1'];
$name = 'Mark';

if ($block1 == $name)
{
echo 'yes';
}
else
{
echo 'no';
}

but i think my reasoning is wrong, im beginner... all solutions are welcome

gege
  • 15
  • 5
  • 1
    You should avoid using mysql_* functions. They are no longer safe to use and will soon be removed from the language as a whole. – César Apr 18 '16 at 15:27
  • Side note: if you're learning, don't waste your time studying the legacy mysql extension, which has been deprecated for years and is no longer part of latest PHP version. It's like learning Latin before a holiday in Rome. – Álvaro González Apr 18 '16 at 15:28

4 Answers4

0

When you use mysql_fetch_array you can't use $row[COLUMN_NAME].

You must use $row[COLUMN_INDEX] or use mysql_fetch_assoc method for fetch by column name.

  $row = mysql_fetch_assoc($res);
  $block1 = $row['block_1'];  

Read more in http://www.w3resource.com/php/function-reference/mysql_fetch_assoc.php

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hamid Abbasi
  • 346
  • 2
  • 14
0

try this:

$sql = 'SELECT * FROM my_table WHERE id="1"';

It may be helpful to stick using double quotes only on the in-side of single quotes. It's not necessary...but it has always helped me in practice in trying to keep track of them. If you pick one, remember to stick with it....you've used single quotes in the rest of your code below:

$name = 'Mark';
echo 'yes';

The above comments are correct....
This is a depreciated way of doing MYSQL calls, please consider this: Are there any security benefits to using PDO::query vs. mysql_query? switching mysql_query() to PDO::query() and learning how it functions will keep you upto date.

Best of luck.

Community
  • 1
  • 1
n8thanael
  • 330
  • 3
  • 10
  • Single-quote vs. double-quote is not just a matter of preference: http://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php – WillardSolutions Apr 18 '16 at 15:50
  • @EatPeanutButter...very true - I think your link is very helpful. – n8thanael Apr 18 '16 at 16:07
-1

You're just missing a quote there

$sql = "SELECT * FROM my_table WHERE id='1'";
César
  • 370
  • 1
  • 9
-1

You can count results with requested variables.

$sql = "SELECT COUNT(*) as total FROM my_table WHERE id='1' AND block_1='Mark'";
$res = mysql_query($sql, $connection);
$row = mysql_fetch_assoc($res);
echo $row['total'] > 0 ? 'yes' : 'no';