0

I've created an API for mySQL database, to get the product data for a given barcode.

It generally works well, I'm able to retrieve all the data with a POST request that has Content-Type application/x-www-form-urlencoded and body parameter for the barcode.

Postman with a barcode parameter and response

However, the issue is when the product for the given barcode contains umlaut(s) - in that case I don't get anything back.

Product that contains umlaut in the name

Postman with that barcode parameter

Also, here's the products.php that I'm using for the request.


// Create connection
$con=mysqli_connect("localhost"," "," "," ");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

//
$barcode = $con->real_escape_string($_POST['barcode']); 
$stmt = $con->prepare("SELECT * FROM products WHERE UPC = ? OR EAN = ?");
$stmt->bind_param("ss", $barcode, $barcode);
$stmt->execute();

// Check if there are results
if ($result = $stmt->get_result())
{
    // Prepares all the results to be encoded in a JSON
    $row = $result->fetch_assoc();

    $product_upc = $row['UPC'];
    $product_ean = $row['EAN'];
    $product_asin = $row['ASIN'];
    $product_name =$row['name'];
    $product_brand =$row['brand'];
    $product_category = $row['category'];
    $product_image =$row['imageURL'];
    $product_ingredients =$row['ingredients'];
    $product = array('UPC' => $product_upc, 'EAN' => $product_ean, 'ASIN' => $product_asin, 'name' => $product_name, 'brand'=> $product_brand, 'category'=> $product_category, 'imageURL'=> $product_image, 'ingredients'=> $product_ingredients);

    // encodes array with results from database
    echo json_encode($product);
}

// Close connections
mysqli_close($con);
?>

(Just to mention that I've tried both with json_encode($product) as well as with json_encode($product, JSON_UNESCAPED_UNICODE) and it's the same)

Any ideas on how I could fix this? Thanks!

nince
  • 1
  • 2
  • 1
    No code is there we are left to just guess – Vinay May 03 '20 at 07:41
  • @Viney You're right, I'm sorry. I've edited the question to include the products.php as well. – nince May 03 '20 at 10:17
  • The recommended way to post your code over here is in text form rather than some image _(which isn't indexable,searchable or versionable)_, but anyway you code looks fine so only problem I can think of might be at is the database. Check which collation does your database use, follow over [here](https://stackoverflow.com/a/5526189/6160662) for more – Vinay May 03 '20 at 13:36
  • What encoding does your form use? – Evert May 03 '20 at 15:01
  • @Viney Thank you. I've edited again to add the code in a text form instead of an image. Also, I edited the collation and character set for the database and table and I've also added mysqli_set_charset($con, "utf8") to the php and it works now! Thanks again! – nince May 03 '20 at 15:14

0 Answers0