I'm trying to convert my MySql code to MySqli. My MySql is working very good, but the MySqli code isn't working (it isn't giving results). I don't know what I did wrong, I'm a "Noob"Programmer. Can you guys please correct my mistakes.
This is my MySql code:
<?php
session_start();
include 'dbh.php';
$name = $_POST['name'];
$desc = $_POST['desc'];
$placerId = $_SESSION['id'];
$null = "0";
if (isset($_SESSION['uid'])) {
$sql = "INSERT INTO adds (name, descr, placerId, imgURL)
VALUES ('$name', '$desc', '$placerId', '$null')";
$result = mysqli_query($conn, $sql);
$str = $_POST['keywords'];
$arr = explode(" ", $str);
$sql = "SELECT * FROM adds WHERE placerId='$placerId' ORDER BY id DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$addId = $row['id'];
//print all the value which are in the array
foreach($arr as $keyword){
$sql = "INSERT INTO keywords (placerId, productId, keyword)
VALUES ('$placerId', '$addId', '$keyword')";
$result = mysqli_query($conn, $sql);
}
And this is my MySqli code:
$name = $_POST['name'];
$desc = $_POST['desc'];
$placerId = $_SESSION['id'];
$null = "0";
if (isset($_SESSION['uid'])) {
if ($stmt = $mysqli->prepare("INSERT INTO adds (name, descr, placerId, imgURL) VALUES (?, ?, ?, ?)")) {
// Bind the variables to the parameter as strings.
$stmt->bind_param("ssss", $name, $desc, $placerId, $null);
// Execute the statement.
$stmt->execute();
// Close the prepared statement.
$stmt->close();
}
$str = $_POST['keywords'];
$arr = explode(" ", $str);
if ($stmt = $mysqli->prepare("SELECT id FROM adds WHERE placerId=? ORDER BY id DESC LIMIT 1")) {
// Bind a variable to the parameter as a string.
$stmt->bind_param("s", $placerId);
// Execute the statement.
$stmt->execute();
// Get the variables from the query.
$stmt->bind_result($addId);
// Fetch the data.
$stmt->fetch();
// Close the prepared statement.
$stmt->close();
foreach($arr as $keyword){
if ($stmt = $mysqli->prepare("INSERT INTO keywords (placerId, productId, keyword) VALUES (?, ?, ?)")) {
// Bind the variables to the parameter as strings.
$stmt->bind_param("sss", $placerId, $addId, $keyword);
// Execute the statement.
$stmt->execute();
// Close the prepared statement.
$stmt->close();
}
}
}
And the ($conn variable to connect to the database) code:
$conn = mysqli_connect("localhost", "root", "", "stp2");
if (!$conn) {
die("Connection failed: ".mysqli_connect_error);
}