I have to add a url into a data-url attribute in a button element

2.7k views Asked by At

I have to add a url into a data-url attribute in a button element. But from the url image, I have to add id and book name which are php variables. How can I add this two php variables in my data-url attribute?

This is the URL : http://localhost/book%20store/detail.php?id=53&cat=Game Of Thrones This is my code (I've tried this but this is not working):

$book_id = $row['b_id'];  
$book_name = $row['b_nm'];    
echo'<table>  
     <tr>  
       <button class="sharer btn btn-lg"   
data-url="http://localhost/book store/detail.php?id={$book_id}&cat={$book_name}" >
       Share to Facebook </button>
     </tr>
      </table>';

from the url : $row['b_id'] = 53
And $row['b_nm']=Game Of Thrones

2

There are 2 answers

1
ATechGuy On BEST ANSWER

Assuming your vars aren't empty then the below should work, your orig wont work as it has single quotes and the vars inside. So use double quotes or the solution in my post below, either should work

    echo '<table>  
     <tr>  
       <button class="sharer btn btn-lg"   
data-url="http://localhost/book store/detail.php?id=' . $book_id . '&cat=' . $book_name . '" >
       Share to Facebook </button>
     </tr>
      </table>';
3
Alex On

I'm not sure I'm understanding your question correctly, but if you are trying to insert PHP variables into a HTML element in your PHP page, you could do it inline like this:

<a href="..." data-url="http://books.matrixmp3bd.com/book%20store/detail.php?id=<?PHP echo $bookId; ?>"></a>

$bookId is whatever your book id variable is.

Please see this question:

Using PHP variables inside HTML tags?

Edit in response to OP's comment and code snippet

In the line of the code you provided, you would just add your $book_id variable in-line to your echo statement:

detail.php?id="'.$book_Id.'"> Share to</button>

Notice I used the . operator to append the variable into the string you were already echoing.