Ramy Alayane
Ramy Alayane

Reputation: 94

SQL Statement not working in php while trying to fetch information from mysql database

I tried everything and I'm losing my mind

    
    function submitItem(){
        textarea = $("#textarea").val();
        status = $("#status").val();
        category = $("#categories").val();
        date = $("#date").val();
            
        var ajaxReq = new XMLHttpRequest();
        ajaxReq.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("message").innerHTML = this.responseText;
            }
        }
        ajaxReq.open("POST","../php/addItem.php",true);
        ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxReq.send("textarea="+textarea+"&category="+category+"&status="+status+"&date="+date);
    }
AJAX REQUEST
<?php
session_start();
require("server.php");
$cnx = new mysqli($server_name,$server_username,$server_password,$db);

$category = $_POST["category"];
$item = $_POST["textarea"];
$date = $_POST["date"];
$status = $_POST["status"];
$userID = $_SESSION["userID"];

$searchForCategory = "SELECT * FROM categories where categoryname = \"".$category."\"";
$result = $cnx->query($searchForStatus);
$row = $result->num_rows;

echo $row;

?>

And I tried everything, when I put and actual name it's working fine. I echo-ed the $category to see if it's working and it's working fine. I have no idea what the error might be

Upvotes: 0

Views: 32

Answers (1)

Barmar
Barmar

Reputation: 780851

The textarea probably contains some special characters, which you aren't encoding properly. Use $.post, which will encode the data properly.

function submitItem() {
    $.post("../php/addItem.php", {
        textarea: $("#textarea").val(),
        category: $("#categories").val(),
        status: $("#status").val(),
        date: $("#date").val()
    }, function(response) {
        $("#message").html(response);
    });
}

If there's some reason you don't want to do this, use the encodeURIComponent() function around each parameter, e.g.

"textarea=" + encodeURIComponent(textarea) + "&category=" + encodeURIComponent(category) + ...

Upvotes: 1

Related Questions