2017-07-17 65 views
0

你好傢伙我想在條帶簡單實現 中使用一個php變量,只有當這個人已經登錄時纔會從數據庫中獲取金額,否則將顯示登錄按鈕。我的問題是,當我把代碼中的回聲聲明PHP變量($量)不正確傳遞anymore.Here是我的代碼:提前Php條形變量

if(isset($_SESSION['u_id'])){ 
       $newId = $_SESSION['u_id']; 
       $sql = "SELECT Amount FROM costumers WHERE id='$newId'"; 
      $result = mysqli_query($conn, $sql); 
      if ($row = mysqli_fetch_assoc($result)){ 
      $amount=$row['Amount']; 
      } 
       echo'<form class = "payment" action="/your-server-side-code" method="POST"> 
<script 
    src="https://checkout.stripe.com/checkout.js" class="stripe-button" 
    data-key="pk_test" 
    data-amount="$amount" 
    data-name="Company" 
    data-description="Card Payment" 
    data-image="https://stripe.com/img/documentation/checkout/marketplace.png" 
    data-locale="auto"> 
</script> 
    <script> 

     document.getElementsByClassName("stripe-button-el")[0].style.display = \'none\'; 
    </script> 
    <button type="submit" class="yourCustomClass">Pay with Card</button> 
</form>'; 
      } else{ 
        echo'<div class="logInButton" onclick = "location.href = \'loginindex.php\'"> 
      <a href="loginindex.php">Login/Sign up</a></div>'; 
       } 

謝謝!

+0

嘗試將'echo'語句中的引號更改爲雙引號 - ''',並且可能(爲了便於閱讀)顯示使用大括號使用變量的位置,因此'echo「data-amount =' {$ amount}'「' – Giedrius

+0

此外,爲了便於閱讀和使用,當您有大量的HTML時,您最好轉義PHP並僅在需要時才放回到PHP中。問題變成'data-amount:=「<?php echo $ amount; ?>「' – Difster

+0

其餘代碼中的雙引號怎麼樣? – Zotov

回答

0

第一次嘗試使用您的迴音的sprintf傳遞$量值是這樣的:

echo sprintf("<form class = 'payment' action='/your-server-side-code' method='POST'> 
<script 
    src='https://checkout.stripe.com/checkout.js' class='stripe-button' 
    data-key='pk_test' 
    data-amount='%s' 
    data-name='Company' 
    data-description='Card Payment' 
    data-image='https://stripe.com/img/documentation/checkout/marketplace.png' 
    data-locale='auto'> 
</script> 
    <script> 

     document.getElementsByClassName('stripe-button-el')[0].style.display = 'none'; 
    </script> 
    <button type='submit' class='yourCustomClass'>Pay with Card</button> 
</form>",$amount); 

然後,通過鍵入的var_dump($量)檢查$量的值,它的類型應該是字符串。

我使用PDO,而不是mysqli的,所以爲了更好的解析id和金額中獲得價值,你可以使用這個:

$db=new pdo("mysql:host=localhost;dbname=madb","user","mdp"); 
$sql = "SELECT Amount FROM costumers WHERE id= ?"; 
$result = $db->prepare($sql); 
$result->execute([$newId]); 
$amount=($result->rowCount()!=0) ? $result->fetch()['Amount'] : "noValue"; 

相反的:

$sql = "SELECT Amount FROM costumers WHERE id='$newId'"; 
     $result = mysqli_query($conn, $sql); 
     if ($row = mysqli_fetch_assoc($result)){ 
     $amount=$row['Amount']; 
     } 

好運。

+0

非常感謝!!!!!! – Zotov

+0

不客氣,將它標記爲已回答? –