D
D
danyfir2017-10-05 22:36:52
PHP
danyfir, 2017-10-05 22:36:52

How to get a variable out of a while loop?

There is a code in which there is a while loop that wanders through the database.

$postID = $_POST['label'];

  if ($proverka == 'da') {
    $db = new Mysqli("localhost", "neskazhu", "neskazhu", "neskazhu");
    $result = mysql_query ("SELECT * FROM mytable WHERE meta_key='subject_name' AND meta_value='$postID'");
    $sql=mysql_fetch_assoc($result);
    while ($row = mysql_fetch_assoc($result)) {
    $buf = $row['post_id'];
    update_post_meta($buf, 'payment', 'Да');
    }
$postID = $buf; //вот тут хочу вытащить последний элемент из цикла, а он не выходит... (мне без разницы, на самом деле, последний или первый достать элемент, мне он нужен просто)
    }

I can't get the $buf variable outside of the while loop (although maybe if doesn't, but that's unlikely). Help!
Or, as an option, without a cycle, somehow get $row['post_id']; the first one ... But I don’t understand how ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nozzy, 2017-10-06
@danyfir

without a cycle to get somehow $row['post_id']; first most...
there is a LIMIT for this:
$result= mysql_query ("SELECT * FROM mytable WHERE meta_key='subject_name' AND meta_value='$postID' LIMIT 1");
$row = mysql_fetch_assoc($result);
echo $row['post_id'];

T
twobomb, 2017-10-05
@twobomb

Try this

$postID = $_POST['label'];

  if ($proverka == 'da') {
    $db = new Mysqli("localhost", "neskazhu", "neskazhu", "neskazhu");
    $result = mysql_query ("SELECT * FROM mytable WHERE meta_key='subject_name' AND meta_value='$postID'");
    $sql=mysql_fetch_assoc($result);
  $buff = 0;
    while ($row = mysql_fetch_assoc($result)) {
    $buf = $row['post_id'];
    update_post_meta($buf, 'payment', 'Да');
    }
$postID = $buf; //вот тут хочу вытащить последний элемент из цикла, а он не выходит... (мне без разницы, на самом деле, последний или первый достать элемент, мне он нужен просто)
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question