A
A
Armand M2015-11-16 20:10:07
PHP
Armand M, 2015-11-16 20:10:07

Same variables how to use?

Sorry for the title, I don't know what to call this question.
I'm learning PHP in general. And I ran into one issue, I just can not figure it out.
When can a variable name be repeated and when not?
For example, here at first there is $result and then it also occurs only for another function:

<?php include("blocks/db.php");
if (isset($_GET['cat'])) {$cat = $_GET['cat'];}
if (!isset ($cat)) {$cat = 1;}

$result = mysql_query("SELECT * FROM category WHERE id='$cat'",$db);

if (!$result)
{
echo "<p>Запрос на выборку данных из базы не прошел. Напишите об этом администратору [email protected] <br>Код ошибки:</p>";
exit(mysql_error());
}

if (mysql_num_rows($result) > 0)
{
$myrow = mysql_fetch_array($result);
}

else
{
echo "<p>Информация по запросу не может быть извлечена. В таблице нет записей</p>";	
exit();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="style.css" rel="stylesheet" type="text/css">
<meta name="description" content="<?php echo $myrow["meta_d"] ?>">
<meta name="keywords" content="<?php echo $myrow["meta_k"] ?>">
<title><?php echo "Рубрика - $myrow[title]" ?></title>
</head>

<body>
<table class="main_table" width="690" border="0" align="center">
  <?php include("blocks/header.php"); ?>
  <tr>
    <td valign="top"><table width="100%" border="0">
      <tr>
       <?php include("blocks/leftnav.php"); ?>
        <td valign="top">
        
<?php 
    
echo $myrow["text"];
    
$result = mysql_query("SELECT id,title,`desc`,date,author,mini_img,view FROM data WHERE cat='$cat'", $db);

if (!$result)
{
echo "<p>Запрос на выборку данных из базы не прошел. Напишите об этом администратору [email protected] <br>Код ошибки:</p>";
exit(mysql_error());
}

if (mysql_num_rows($result) > 0)
{
  $myrow = mysql_fetch_array($result);

  do
  {
  printf ("<table border='0'>
            			<tr>
            				<td>
                <p><img align='left' src='%s'><a href='view_post.php?id=%s'>%s</a></p>
                <p>Дата добавления: %s</p>
                <p>Автор: %s</p>
              </td>
            			</tr>
            
            			<tr>
              				<td>%s<br><p>Просмотров: %s</p></td>
            			</tr>
          			</table><br><br>", $myrow['mini_img'], $myrow['id'], $myrow['title'], $myrow['date'], $myrow['author'], $myrow['desc'], $myrow['view']);
  }
  while ($myrow = mysql_fetch_array($result));
}

else
{
  echo "<p>Информация по запросу не может быть извлечена. В таблице нет записей</p>";	
  exit();
}
    
?>
        
        
        
        </td>
      </tr>
    </table></td>
  </tr>
  <?php include("blocks/footer.php"); ?>
</table>
</body>
</html>

And here I had to do the second $result3 :
<?php include("blocks/db.php");
if (isset($_GET['cat'])) {$cat = $_GET['cat'];}
if (!isset ($cat)) {$cat = 1;}

$result = mysql_query("SELECT * FROM category WHERE id='$cat'",$db);

if (!$result)
{
echo "<p>Запрос на выборку данных из базы не прошел. Напишите об этом администратору [email protected] <br>Код ошибки:</p>";
exit(mysql_error());
}

if (mysql_num_rows($result) > 0)
{
$myrow = mysql_fetch_array($result);
}

else
{
echo "<p>Информация по запросу не может быть извлечена. В таблице нет записей</p>";	
exit();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="style.css" rel="stylesheet" type="text/css">
<meta name="description" content="<?php echo $myrow["meta_d"] ?>">
<meta name="keywords" content="<?php echo $myrow["meta_k"] ?>">
<title><?php echo "Рубрика - $myrow[title]" ?></title>
</head>

<body>
<table class="main_table" width="690" border="0" align="center">
  <?php include("blocks/header.php"); ?>
  <tr>
    <td valign="top"><table width="100%" border="0">
      <tr>
       <?php include("blocks/leftnav.php"); ?>
        <td valign="top">
        
<?php 
    
echo $myrow["text"];
    
$result = mysql_query("SELECT id,title,`desc`,date,author,mini_img,view FROM data WHERE cat='$cat'", $db);

if (!$result)
{
echo "<p>Запрос на выборку данных из базы не прошел. Напишите об этом администратору [email protected] <br>Код ошибки:</p>";
exit(mysql_error());
}

if (mysql_num_rows($result) > 0)
{
  $myrow = mysql_fetch_array($result);

  do
  {
  printf ("<table border='0'>
            			<tr>
            				<td>
                <p><img align='left' src='%s'><a href='view_post.php?id=%s'>%s</a></p>
                <p>Дата добавления: %s</p>
                <p>Автор: %s</p>
              </td>
            			</tr>
            
            			<tr>
              				<td>%s<br><p>Просмотров: %s</p></td>
            			</tr>
          			</table><br><br>", $myrow['mini_img'], $myrow['id'], $myrow['title'], $myrow['date'], $myrow['author'], $myrow['desc'], $myrow['view']);
  }
  while ($myrow = mysql_fetch_array($result));
}

else
{
  echo "<p>Информация по запросу не может быть извлечена. В таблице нет записей</p>";	
  exit();
}
    
?>
        
        
        
        </td>
      </tr>
    </table></td>
  </tr>
  <?php include("blocks/footer.php"); ?>
</table>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
danforth, 2015-11-16
@muaythai075

In your case, the need for the variable simply disappeared.
Read about scopes in PHP. There are two of them: global and local . Those in the context of a function are local. Outside - global. If you need to make a variable in a function global, use global.
Also, at the beginning there is this code:
if (isset($_GET['cat'])) {$cat = $_GET['cat'];}
if (!isset ($cat)) {$cat = 1;}
Use if-else.

S
Stalker_RED, 2015-11-16
@Stalker_RED

Read about scope .
In some cases, if you are SURE that a variable is no longer needed, you can reuse it for some other purpose. But it is better not to abuse it, because. reading and debugging such code is much more difficult.
And yes, scope is structured differently in different languages.
UPD: This is off topic for your question, but you can't do that.

<?php include("blocks/db.php");
if (isset($_GET['cat'])) {$cat = $_GET['cat'];}
if (!isset ($cat)) {$cat = 1;}

$result = mysql_query("SELECT * FROM category WHERE id='$cat'",$db);

Because if someone makes such a get request, then such a request
will go to the database
SELECT * FROM category WHERE id='0';drop table category;--'
Or another, stealing passwords, for example.
It's better to do something like this:
$cat = filter_input(INPUT_GET, "cat", FILTER_SANITIZE_NUMBER_INT);
if (empty($cat)) $cat = 1;

This will ensure that only a number or null is retrieved from $_GET['cat'] .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question