I'd like to select a random YouTube video from

2019-07-11 03:04发布

问题:

I have a MySQL database table called 'Videos' with only three columns (fields?): ID, EmbedURL, and Name.

I'd like to use PHP (or something, anything) in the actual index.html to grab a random YouTube video from the DB and put the EmbedURL into an iFrame so that when the user clicks a button (or refreshes the page) another random video from the database loads.

I know I could do this with an iframe embed, like so:

<iframe width="560" height="315" src="http://www.youtube.com/embed/T0Jqdjbed40?playlist=SyoA4LXQco4,6l6PPvUhR4c" frameborder="0" allowfullscreen></iframe>

But I really want this simple, 1-page website to have a big, fun, attractive button to click, and the iframe embed player just has this boring "next" button.

Below is my code so far. As a starter step, I was just trying to see if I could get my page to display the EmbedURL that's saved in the database, but it's not echoing anything on the page, and I know it's not addressing the iframe issue.

I did a pretty thorough search (60min) and can't quite put the pieces together. The query is working in phpMyAdmin.

Any pointers appreciated.

[EDIT: My webhost is running PHP v. 5.2.17].

<?php
    mysql_connect("localhost", "admin", "xxxxxxx") or die(mysql_error());
    mysql_select_db ("my_db_name") or die(mysql_error());

    $select = mysql_query("SELECT EmbedURL FROM `Videos` ORDER BY RAND() LIMIT 1");
   while($row = mysql_fetch_assoc($select)) {
?>              

    <p><?php echo $row ['EmbedURL']  ?></p>

回答1:

It looks like they are deprecating the mysql calls and recommend using the mysqli object oriented calls instead.

http://us3.php.net/manual/en/function.mysql-connect.php

<?php
    $mysqli = new mysqli("host", "username", "password", "database name");
    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    }
    echo $mysqli->host_info . "\n";

    $res = $mysqli->query("SELECT EmbedURL FROM `Videos` ORDER BY RAND() LIMIT 1");
    $row = $res->fetch_assoc();
?>            

<iframe width="560" height="315" src="<?php echo $row['EmbedURL']; ?>" frameborder="0" allowfullscreen></iframe>

<p><?php echo $row['EmbedURL'];?></p>

This worked for me on my local server running php 5.4. The first comment on the constructor recommends using a different set of commands if you are are using a php version below 5.2.9.



回答2:

Is that the script you are running? The last line seems to be missing a semicolon.

Otherwise it seems fine. Although, as pointed out by Marc B, you do not need to use a while loop if it is just one. And as mentioned by Fanis, you should do error checking.