简体   繁体   English

解决关联数组中SQL查询的返回值

[英]Solving the return value of an SQL Query in an Associative Array

Once again I am at the mercy of your knowledge and hope you can help. 我再次受您的知识左右,并希望您能提供帮助。

Actual question is the bold italics, however you won't be able to help without reading the information that I've given. 实际的问题是粗体斜体,但是如果不阅读我提供的信息,您将无法提供帮助。

Background to Question - I'm creating a photography website (for my mum) using HTML, CSS, MySQL and PHP. 问题背景-我正在使用HTML,CSS,MySQL和PHP创建一个摄影网站(针对我的妈妈)。 I'm in the process of working on the database, specifically on allowing my mum to insert images into the database using this form ( http://i.imgur.com/h4nXFFA.png ). 我正在研究数据库,特别是允许妈妈使用这种形式( http://i.imgur.com/h4nXFFA.png )将图像插入数据库。 She has no idea how to code, therefore I need to make it easy for her. 她不知道如何编码,因此我需要简化她的工作。

Database Background (what you need to know) - I've got an image_tbl and album_tbl . 数据库背景(您需要知道的)-我有一个image_tblalbum_tbl The album_tbl is shown here - http://i.imgur.com/4GXh9MP.png - with each album having an ID and Name (forget the 'hidden'). 此处显示了album_tbl- http ://i.imgur.com/4GXh9MP.png-每个专辑都有ID和名称(忘了“隐藏”)。 The image_tbl is shown here - http://i.imgur.com/RgC35Nd.png - with the important part (for this question) being the albumName. -该image_tbl如下所示http://i.imgur.com/RgC35Nd.png -与重要的组成部分(这个问题)作为ALBUMNAME。

Aim - I've managed to populate the 'Insert a New Image' form with the albums from album_tbl (picture shows 'Exploration'). 目的-我设法用album_tbl中的相册填充了“插入新图像”表单(图片显示为“ Exploration”)。 I want her to be able to click the AlbumName (so she knows what album to add to), yet I want the image she inserts to receive the albumID in the database. 我希望她能够单击AlbumName(以便她知道要添加到哪个相册),但是我希望她插入的图像能够在数据库中接收AlbumID。 Here's a Pastebin of my code thus far. 到目前为止,这是我的代码的Pastebin

http://pastebin.com/6v8kvbGH = The HTML Form , for helping me be aware of the 1st Form in the code... http://pastebin.com/6v8kvbGH = HTML表单 ,可帮助我了解代码中的第一个表单...

http://pastebin.com/4X6abTey = PHP/MySQL Code . http://pastebin.com/4X6abTey = PHP / MySQL代码 Here we have me calling the inputs in the form and using them in 2 SQL Queries. 在这里,我们让我以表格的形式调用输入,并在2个SQL查询中使用它们。 The first Query is aiming to get the albumID of the albumName that was entered, and this is where it goes wrong. 第一个查询的目的是获取所输入专辑名称的专辑ID,这就是问题所在。 The commented out statements (using //) are me error-checking, and albumName is passed on from the form. 注释掉的语句(使用//)正在进行错误检查,并且albumName从表单传递。 However, the number of rows returned from the 1st SQL Statement is 0, when it should be 1. This is where I need help as clearly something's wrong with my assoc array ... 但是,从第一个SQL语句返回的行数应该为1时为0。这是我需要帮助的地方,因为assoc数组显然有问题...

2nd Aim - Once the 1st SQL Query is working, the 2nd SQL Query is hopefully going to input the required variables into image_tbl including the albumID I hopefully just got from the 1st SQL Query. 第二个目标-第一个SQL查询工作后,第二个SQL查询有望将所需的变量输入到image_tbl中,包括我希望从第一个SQL查询中获得的albumID。

I hope this is all that's required, as far as I'm aware the people who understand this should be able to help with what I've given. 我希望这是所需要的,据我所知,了解这些的人应该可以为我提供的帮助。 Thanks very much in advance! 首先十分感谢!

Jake 杰克

Someone asked me to paste the code - HTML Form: 有人要求我粘贴代码-HTML表单:

    <h2>Insert a new image</h2><br>

    <form action="imagesInsert.php" method="POST" enctype="multipart/form-data">

        Name of Image: <input type="text" name="name" /><br>

        Date: <input type="text" name="dateTime" /><br>

        Caption: <input type="text" name="caption" /><br>

        Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>

        Slideshow: <input type="text" name="slideshow" /><br>

        Choose an Album to place it in: 

            <?php
            mysql_connect('localhost', 'root', '');
            mysql_select_db('admin_db');

            $sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
            $result = mysql_query($sql); ?>

            <select name='albumName'>; <?php
            while ($row = mysql_fetch_array($result)) {
                echo "<option value='" . $row['albumName'] . "'->" . $row['albumName'] . "</option>";
            }
            ?> </select>


        <input type="submit" name="submit"/><br>
    </form>



    <h2>Hide the Image</h2><br>

    <form action="imagesHidden.php" method="POST" enctype="multipart/form-data">

        Title: 

            <?php
            mysql_connect('localhost', 'root', '');
            mysql_select_db('admin_db');

            $sql = "SELECT name FROM image_tbl WHERE hidden = false";
            $result = mysql_query($sql);

            echo "<select name='name'>";
            while ($row = mysql_fetch_array($result)) {
                echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
            }
            echo "</select>";
            ?>

            <input type="submit" value="Hide" name="submit">

    </form>



    <h2> Renew from Hidden Items </h2><br>

    <form action="imagesRestore.php" method="POST" enctype="multipart/form-data">

        Title: 

            <?php
            mysql_connect('localhost', 'root', '');
            mysql_select_db('admin_db');

            $sql = "SELECT name FROM image_tbl WHERE hidden = true";
            $result = mysql_query($sql);

            echo "<select name='name'>";
            while ($row = mysql_fetch_array($result)) {
                echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
            }
            echo "</select>";
            ?>

            <input type="submit" value="Renew / Un-Hide" name="submit">

    </form>


</body>

Inserting the image using PHP/MySQL: 使用PHP / MySQL插入图像:

    <?php

$username="root";
$password="";
$database="admin_db";
$servername="localhost";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) 
{
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully <br><hr>";

$name        = $_POST['name'];
$dateTime    = $_POST['dateTime'];
$caption     = $_POST['caption'];
$comment     = $_POST['comment'];
$slideshow   = $_POST['slideshow'];
$hidden      = false;
$albumName   = $_POST['albumName'];

// echo "album name is" . $albumName;

$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
$albumID = $conn->query($sql);

// echo "Number of rows is " . $albumID->num_rows;

if ($albumID->num_rows > 0) {
    // output data of each row
    while($row = $albumID->fetch_assoc()) {
        echo "Album ID: " . $row["albumID"]. "<br>";
    }
} else {
    echo "0 results";
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

$new_comment = str_replace("'", "''", $comment);

$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";

$result = $conn->query($sql);

if ($result)
{
    echo "Data has been inserted";
} 
else
{
    echo "Failed to insert";
}

$conn->close();
?>

This line: 这行:

$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";

should be: 应该:

$sql = "SELECT albumID FROM album_tbl WHERE albumName = '$albumName'";

since the album name is a string. 因为专辑名称是一个字符串。

You should check for errors when you perform a query: 执行查询时,应检查错误:

$albumID = $conn->query($sql) or die($conn->error);

You can't use $albumID in the INSERT query. 您不能在INSERT查询中使用$albumID Despite the name of the variable, it doesn't contain an album ID, it contains a mysqli_result object that represents the entire resultset of the query -- you can only use it with methods like num_rows and fetch_assoc() to extract information from the resultset. 尽管有变量的名称,但它不包含相册ID,它包含一个mysqli_result对象,该对象表示查询的整个结果集-您只能将其与num_rowsfetch_assoc()类的方法一起使用,以从结果fetch_assoc()提取信息。

What you can do is use a SELECT statement as the source of data in an UPDATE : 您可以做的是使用SELECT语句作为UPDATE的数据源:

$stmt = $conn->prepare("INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) 
    SELECT ?, ?, ?, ?, ?, ?, albumID
    FROM album_tbl
    WHERE albumName = ?";
$stmt->bind_param("sssssss", $name, $dateTime, $caption, $comment, $slideshow, $hidden, $albumName);
$stmt->execute();

Note that when you use a prepared query, you don't need to fix the quotes in $comment (which you should have done using $conn->real_escape_string($comment) , not str_replace() ). 请注意,当您使用准备好的查询时,不需要固定$comment的引号(您应该使用$conn->real_escape_string($comment)而不是str_replace() )。

Just to help you understand, this can also be done without a prepared query. 只是为了帮助您理解,这也可以在没有准备好的查询的情况下完成。

$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) 
    SELECT '$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', albumID
    FROM album_tbl
    WHERE albumName = '$albumName'";

First of all create a single database connection let say 首先创建一个数据库连接让我们说

db_connection.php db_connection.php

<?php
    $username="root";
    $password="1k9i2n8gjd";
    $database="admin_db";
    $servername="localhost";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);

    // Check connection
    if ($conn->connect_error){
        die("Connection failed: " . $conn->connect_error);
    }

    echo "Connected successfully <br><hr>";

Then in your form or any php file that needs database connection you can just include the db_connection.php so that you have one database connection. 然后,在您的表单或需要数据库连接的任何php文件中,只需包含db_connection.php ,即可建立一个数据库连接。

Note: I have change the value of option to albumId so that you dont need to query or select based on albumName because you already have the albumID passed in imagesInsert.php via $_POST 注意:我已将option的值更改为albumId,因此您无需基于albumName进行查询或选择,因为您已经具有通过$ _POST在imagesInsert.php中传递的albumID

<?php 
   require_once('db_connection.php');
   //include_once('db_connection.php');
?>
<html>
<head>
    <title>Admin Page | Alison Ryde's Photography</title>
    <link rel="stylesheet" type="text/css" href="../../css/style.css">
</head>
    <body>

        <h2>Insert a new image</h2><br>

        <form action="imagesInsert.php" method="POST" enctype="multipart/form-data">

            Name of Image: <input type="text" name="name" /><br>

            Date: <input type="text" name="dateTime" /><br>

            Caption: <input type="text" name="caption" /><br>

            Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>

            Slideshow: <input type="text" name="slideshow" /><br>

            Choose an Album to place it in:

                <?php

                $sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
                $result = $conn->query($sql);// mysql_query($sql); ?>

                <select name='albumName'>; <?php
                while ($row = $result->fetch_array()) {
                    echo "<option value='" . $row['albumID'] . "'->" . $row['albumName'] . "</option>";
                }
                ?> </select>


            <input type="submit" name="submit"/><br>
        </form>



        <h2>Hide the Image</h2><br>

        <form action="imagesHidden.php" method="POST" enctype="multipart/form-data">

            Title:

                <?php


                $sql = "SELECT name FROM image_tbl WHERE hidden = false";
                $result = $conn->query($sql);//mysql_query($sql);

                echo "<select name='name'>";
                while ($row = $result->fetch_array()) {
                    echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
                }
                echo "</select>";
                ?>

                <input type="submit" value="Hide" name="submit">

        </form>



        <h2> Renew from Hidden Items </h2><br>

        <form action="imagesRestore.php" method="POST" enctype="multipart/form-data">

            Title:

                <?php


                $sql = "SELECT name FROM image_tbl WHERE hidden = true";
                $result = $conn->query($sql);//mysql_query($sql);

                echo "<select name='name'>";
                while ($row = $result->fetch_array()) {
                    echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
                }
                echo "</select>";
                ?>

                <input type="submit" value="Renew / Un-Hide" name="submit">

        </form>


    </body>
</html>

Then in your php code that inserts the data should be like this. 然后在您的PHP代码中,插入数据应该是这样的。

imagesInsert.php imagesInsert.php

<?php 
       require_once('db_connection.php');
       //include_once('db_connection.php');

$name        = $_POST['name'];
$dateTime    = $_POST['dateTime'];
$caption     = $_POST['caption'];
$comment     = $_POST['comment'];
$slideshow   = $_POST['slideshow'];
$hidden      = false;
$albumID     = $_POST['albumName'];


$new_comment = str_replace("'", "''", $comment);

$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";

$result = $conn->query($sql);

if ($result)
{
    echo "Data has been inserted";
}
else
{
    echo "Failed to insert";
}

$conn->close();
?>

Another piece of advice is to use prepared statementif your query is build by users input to avoid sql injection 如果您的查询是由用户输入构建的,则另一条建议是使用准备好的语句,以避免sql注入

 <?php 
           require_once('db_connection.php');
           //include_once('db_connection.php');
    $name        = $_POST['name'];
    $dateTime    = $_POST['dateTime'];
    $caption     = $_POST['caption'];
    $comment     = $_POST['comment'];
    $slideshow   = $_POST['slideshow'];
    $hidden      = false;
    $albumID     = $_POST['albumName'];


    $new_comment = str_replace("'", "''", $comment);
 $sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES (?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $name, $dateTime, $caption,$new_comment,$slideshow,$hidden,$albumID);
$stmt->execute();

hope that helps :) good luck 希望有帮助:)祝你好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM