简体   繁体   中英

Save canvas as image into database with jquery and php

So, I'm wondering what I'm doing wrong in my code. I have a <canvas> element which can be drawn on. On mouseup jQuery pulls the data as an image and should then post it to PHP, which stores it in the database. It's not working though.

function print(){
    var canvas1 = document.getElementById("paint");
    var ctx1 = canvas1.getContext("2d");
    var img = canvas1.toDataURL("image/png");
    img = encodeURIComponent(img);

    $.ajax({
        url: 'poster.php',
        data: { data: img },
                type: 'post',
                success: function(data) {
                    console.log(data);
                }
    });

poster.php

<?php

    $data = $_POST['data'];

    $server = "localhost";
    $username = "root";
    $password = "root";
    $database = "canvas";
    $bd = mysql_connect($server, $username, $password) or die("1");
    $ok = mysql_select_db($database, $bd) or die("2");

    $sql = "INSERT INTO canvas (image) VALUES ($data)";
    $qry = mysql_query($sql);

    echo $qry;

?>

Do in your poster.php script to see if your ajax is feeding it something. 来查看您的Ajax是否正在喂食它。 Then modify the following:

    $sql = "INSERT INTO canvas (image) VALUES ($data)";
    $qry = mysql_query($sql);

to:

    $sql = "INSERT INTO canvas (image) VALUES ($data)";
    if( ! mysql_query($sql) )
   {
       echo "Error: " . mysql_error();
   }

Maybe output from the above will show the way to go!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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