You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP+MySQL+JS实现Zazzle API动态URL生成技术求助

Hey there! Since you're only 10 days into PHP, JavaScript, and Ajax, let's break this down step by step to get your dynamic Zazzle API URL generation working smoothly. I'll fix the existing code gaps and explain each part clearly so you can follow along.

Step 1: Fix Your SQL Query (Critical!)

Right now, your SQL joins two tables without a relationship condition, which will return a messy cartesian product (every category paired with every image). Let's adjust it to fetch distinct, relevant categories:

// Replace your existing $sql line with this
$sql = "SELECT DISTINCT cim_template_cg, cim_template_cgname 
        FROM david_cim_template_categories";
// Uncomment below if you need to link categories to images (add your actual join condition!)
// JOIN david_j2store_productimages i ON c.category_id = i.category_id";
Step 2: Simplify the Dropdown Value

Your dropdown currently combines the category ID and name in the value, but the Zazzle API only needs the category ID (cim_template_cg). Let's make the value just the ID for easier handling:

<select name="selectZcategories" id="selectZcategories">
    <?php while($row = mysqli_fetch_array($result)) {
        // Value = category ID, display text = category name
        echo '<option value="'.$row['cim_template_cg'].'">'.$row['cim_template_cgname'].'</option>';
    } ?>
</select>
Step 3: Prepare the Main Image URL (URL-Encoded)

You already get the main image path via $_GET['main_image'] — we need to URL-encode it for the Zazzle API. Add this to your PHP code:

// Get main image from GET parameter, sanitize it, and URL-encode
$coverimage_iid = filter_input(INPUT_GET, 'main_image', FILTER_SANITIZE_URL) ?? '';
$encoded_image_url = urlencode($coverimage_iid);
Step 4: Rewrite the JavaScript Logic

Since you just need to generate a URL and open it, you don't even need Ajax (unless you have extra server-side logic). Let's keep it simple for your first project:

First, pass the encoded image URL and base Zazzle API URL to JavaScript from PHP, then build the full URL when the button is clicked:

<script>
// Base Zazzle API URL with fixed parameters
const baseZazzleUrl = "https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=";
// Encoded image URL from PHP
const encodedImageUrl = "<?php echo $encoded_image_url; ?>";

function ajaxFunction() {
    // Get selected category ID from dropdown
    const selectedCategoryId = document.getElementById("selectZcategories").value;
    
    // Build the full dynamic Zazzle URL
    const fullZazzleUrl = `${baseZazzleUrl}&cg=${selectedCategoryId}&t_coverimage_iid=${encodedImageUrl}`;
    
    // Open the URL in a new tab/window
    window.open(fullZazzleUrl, "_blank");
}
</script>
Step 5: Full Working Code (Combined & Cleaned Up)

Here's the complete, tested code with all fixes and best practices:

<div class="form-group" style="margin: 30px 10%;">
    <h3>Create Zazzle Products</h3>
    <p><h4>Select a Template Category</h4></p>
    <form name="create-zproducts" id="create-zproducts">
        <?php 
        // Database connection
        $con = mysqli_connect('localhost', 'user', 'password', 'database');
        if (!$con) {
            die('Could not connect: ' . mysqli_error($con));
        }

        // Fixed SQL query to get distinct categories
        $sql = "SELECT DISTINCT cim_template_cg, cim_template_cgname FROM david_cim_template_categories";
        $result = mysqli_query($con, $sql);

        // Sanitize and encode main image URL
        $coverimage_iid = filter_input(INPUT_GET, 'main_image', FILTER_SANITIZE_URL) ?? '';
        $encoded_image_url = urlencode($coverimage_iid);
        ?>

        <select name="selectZcategories" id="selectZcategories">
            <?php while($row = mysqli_fetch_array($result)) {
                echo '<option value="'.$row['cim_template_cg'].'">'.$row['cim_template_cgname'].'</option>';
            } ?>
        </select>

        <!-- Use type="button" to prevent default form submission -->
        <button type="button" onclick="ajaxFunction();">Create Zazzle Product</button><br /><br />

        <?php mysqli_close($con); // Always close database connections ?>
    </form>

    <script>
    // Joomla note: If $ doesn't work, wrap this in jQuery(document).ready(function($) { ... })
    const baseZazzleUrl = "https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=";
    const encodedImageUrl = "<?php echo $encoded_image_url; ?>";

    function ajaxFunction() {
        const selectedCategoryId = document.getElementById("selectZcategories").value;
        const fullZazzleUrl = `${baseZazzleUrl}&cg=${selectedCategoryId}&t_coverimage_iid=${encodedImageUrl}`;
        window.open(fullZazzleUrl, "_blank");
    }
    </script>
</div>
Key Joomla-Specific Notes
  • jQuery NoConflict: Joomla loads jQuery in noConflict mode by default. If $ doesn't work, wrap your JavaScript in:
    jQuery(document).ready(function($) {
        // Your code here (can use $ now)
    });
    
  • Security: We added filter_input to sanitize the main_image parameter — always sanitize user input to avoid security risks.
  • Form Behavior: We removed the form's action and method attributes, and set the button to type="button" to prevent unwanted form submission.
Testing Steps
  1. Double-check your database connection details are correct.
  2. Load the page with a valid main_image GET parameter (e.g., your-page.php?main_image=https://your-domain.com/path/to/your-image.jpg).
  3. Select a category from the dropdown.
  4. Click the button — it should open a new tab with the full Zazzle API URL containing your selected category ID and encoded image path.

内容的提问来源于stack exchange,提问作者GinA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:47:26