MySQL not inserting data from php [duplicate] - php

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
I’m having some problems with my database.
MySQL database is organized as:
——————————————————————
userId | value
——————————————————————
63 | {"pro":true}
The GET requests are working just fine but not the POST requests.
POST requests return me just nothing, when it should return a JSON with a success index.
This is my index.php code:
<?php
$database = "";
$username = "";
$password = "";
$servename = "localhost";
$connection = new mysqli($servername, $username, $password, $database);
if ($connection->connect_error) {
die("Connection failure: ".$connection->$connection_error);
}
header("Content-type: application/json");
if ($_SERVER["REQUEST_METHOD"] == "GET") {
if ($_GET["userId"]) {
$result = $connection->query("SELECT value FROM main_table WHERE userId = ".$_GET["userId"]);
if ($result->num_rows > 0) {
echo $result;
}
else {
echo json_encode(array());
}
}
}
elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST["userId"] && $_POST["value"]) {
$result = $connection->query("INSERT INTO main_table (userId, value) VALUES ('".$_POST["userId"]."', '".$_POST["value"]."')");
if ($result) {
echo json_encode(array("success" => TRUE));
}
else {
echo json_encode(array("success" => FALSE));
}
}
}
$connection->close();
?>
Could you guys spot any mistakes in my code?
Thank you in advance!

your code is not secure ,Use this to avoid sql injection
Simple you can should as below code ..also better safety
For select
$query = "
SELECT *
FROM main_table
WHERE userId= ?
";
$stmt = $connection->prepare($query);
$userId=$_GET["userId"];
$stmt->bind_param("i", $userId);
$result = $stmt->get_result();
$rows=[];
while ($data = $result->fetch_assoc())
{
$rows[] = $data;
}
echo json_encode($rows);
Insert for example
$stmt = $connection->prepare("INSERT INTO main_table (value,userId) VALUES (?, ?)");
$stmt->bind_param("ii", $_POST['value'], $_POST['userId']);
if($stmt->execute())
{
echo "insert successful";
}
else
{
echo "couldn't insert successful";
}
$stmt->close();

Related

How to fix HTTP 500 Error during Form Submission? [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
How do I get PHP errors to display?
(27 answers)
Closed 12 months ago.
I created a form with the following fields I am getting a HTTP ERROR 500 message when I hit SUBMIT button on my form. I have created the database as a MySQL database with 4 fields. My PHP code looks like below.
<?php
$yname = $_POST['yname'];
$pname = $_POST['pname'];
$details = $_POST['details'];
$links = $_POST['links'];
if (!empty($yname) || !empty($pname) || !empty($details) || !empty($links)) {
$host = "localhost";
$dbUsername = "u172756077_admin";
$dbPassword = "";
$dbname = "u172756077_Form";
$conn = new mysqli($host, $username, $dbPassword, $dbname);
if (mysqli_connect_error()) {
die('Connect Error('. mysqli_connect_errno().')'.mysqli_cnnect_error());
}
else {
$SELECT = "SELECT pname From form Where pname = ? Limit 1";
$INSERT = "INSERT Into form (yname, pname, details, links) values(?, ?, ?, ?)";
$stmt = $conn->prepare($SELECT);
$stmt->bind_param("s", $pname);
$stmt->execute();
$stmt->bind_result($pname);
$stmt->store_result();
$stmt->fetch();
$rnum = $stmt->num_rows;
if ($rnum == 0) {
$stmt->close();
$stmt = $conn->prepare($Insert);
$stmt->bind_param("ssss",$yname, $pname, $details, $links);
if ($stmt->execute()) {
echo "New record inserted sucessfully.";
}
else {
echo $stmt->error;
}
}
else {
echo "Someone already registers using this email.";
}
$stmt->close();
$conn->close();
}
}
else {
echo "All fields are required.";
die();
}
else {
echo "Submit button is not set.";
}
?>

No data supplied for parameters in prepared statement - error php MySQLi [duplicate]

This question already has an answer here:
"No data supplied for parameters in prepared statement"
(1 answer)
Closed 1 year ago.
i'm very new to php. So, I tried to make a simple form to order sandwiches, but when I click the submit button i get this error "No data supplied for parameters in prepared statement".
Btw, I copied most of the code from a YouTube video, and I don't know what some parts of the code actually do.
that's my code:
<?php
if (isset($_POST['submit'])) {
if (isset($_POST['nombre']) && isset($_POST['apellido']) &&
isset($_POST['bocadillo']) && isset($_POST['extra']) &&
isset($_POST['comentario']) && isset($_POST['comentario'])) {
$nombre = $_POST['nombre'];
$apellido = $_POST['apellido'];
$bocadillo = $_POST['bocadillo'];
$extra = $_POST['extra'];
$comentario = $_POST['comentario'];
$host = "localhost";
$dbUsername = "------";
$dbpassword = "------";
$dbName = "------";
$conn = new mysqli($host, $dbUsername, $dbpassword, $dbName);
if ($conn->connect_error) {
die('Could not connect to the database.');
}
else {
$Select = "SELECT extra FROM pedidos WHERE extra = ? LIMIT 1";
$Insert = "INSERT INTO pedidos(nombre, apellido, bocadillo, extra, comentario) values(?, ?, ?, ?, ?)";
$stmt = $conn->prepare($Select);
$stmt->execute();
$stmt->bind_result($resultemail);
$stmt->store_result();
$stmt->fetch();
$rnum = $stmt->num_rows;
if ($rnum == 0) {
$stmt->close();
$stmt = $conn->prepare($Insert);
if ($stmt->execute()) {
echo "New record inserted sucessfully.";
}
else {
echo $stmt->error;
}
}
else {
echo "Someone already registers using this email.";
}
$stmt->close();
$conn->close();
}
}
else {
echo "All field are required.";
die();
}
}
else {
echo "Submit button is not set";
}
?>
You're missing the bind_param statements for both queries
$Select = "SELECT extra FROM pedidos WHERE extra = ? LIMIT 1";
$stmt = $conn->prepare($Select);
$stmt->bind_param("s", $extra);
$stmt->execute();
and then in the insert
$Insert = "INSERT INTO pedidos(nombre, apellido, bocadillo, extra, comentario) values(?, ?, ?, ?, ?)";
$stmt = $conn->prepare($Select);
$stmt->bind_param("sssss", $nombre, $apellido, $bocadillo, $extra, $comentario);
$stmt->execute();
https://www.w3schools.com/php/php_mysql_prepared_statements.asp

When opening the website, it says it cannot handle the request. Why?

I was hoping someone could help me figure why this code is not really working.
When i enter my website (with the GET), it says the server could not handle the request.
Could someone spot any errors?
I'm new to MySQL/MySQLi and PHP as well, so i'm sorry if any part of my code sounds pretty dumb.
Thanks in advance!!!
My table has the following organization:
-------------------
id | value
-------------------
|
|
-------------------
The column 'id' is an INT and the column 'value' is a JSON.
Here's my current code inside a script called "index.php".
<?php
$database = "...";
$username = "...";
$password = "...";
$servername = "localhost";
$mysqli = new mysqli($servername, $username, $password, $database);
if ($mysqli->connect_error) {
die("Connection failed: ".$mysqli->connect_error.".");
}
header("Content-type: application/json");
function get($id) {
if ($id) {
$query = "SELECT value FROM myTable WHERE id = ?";
$statement = $mysqli->prepare($query);
$statement->bind_param("i", $id);
$statement->execute();
$statement->bind_result($result);
$statement->fetch();
$statement->close();
if ($result) {
return $result;
}
else {
return NULL;
}
}
else {
return NULL;
}
}
function set($id, $value) {
if ($id && $value) {
$filled = get($id);
if ($filled) {
$query = "UPDATE myTable SET value = ? WHERE id = ?";
$statement = $mysqli->prepare($query);
$statement->bind_param("si", $value, $id);
$statement->execute();
$statement->bind_result($result);
$statement->fetch();
$statement->close();
if ($result) {
return TRUE;
}
else {
return FALSE;
}
}
else {
$query = "INSERT INTO myTable (id, value) VALUES (?, ?)";
$statement = $mysqli->prepare($query);
$statement->bind_param("is", $id, $value);
$statement->execute();
$statement->bind_result($result);
$statement->fetch();
$statement->close();
if ($result) {
return TRUE;
}
else {
return FALSE;
}
}
}
else {
return NULL;
}
}
$method = $_SERVER["REQUEST_METHOD"];
if ($method == "GET") {
$result = get($_GET["id"]);
echo $result;
}
elseif ($method == "POST") {
$result = set($_POST["id"], $_POST["value"]);
echo $result;
}
$mysqli->close();
?>

Creating MySQL Prepared Statement

I have absolutely zero experience protecting my SQL data. I am trying to prevent injection attacks on my web service by using prepared statements. I've followed several tutorials, but each one I've implemented has killed my PHP script. How could I protect this query?
$value = (integer)$_GET["name"];
$sql = "SELECT `coordinates`, `center` , `content_string` FROM Regions WHERE `id` = {$value}";
$result = $conn->query($sql);
$rows = array();
if ($result->num_rows > 0) {
// output data of each row
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
}
Here is my attempt:
$value = (integer)$_GET["name"];
$sql = $dbConnection->prepare('SELECT `coordinates`, `center` , `content_string` FROM Regions WHERE `id` = ?');
$sql->bind_param('i', $value);
$sql->execute();
$result = $sql->get_result();
$rows = array();
if ($result->num_rows > 0) {
// output data of each row
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
}
I'm not really sure why this code doesn't work.
You will have to bind the result and below is the code - it is going to work please try it. please check if there any syntax issues in my code. otherwise it will work.
$value = (integer)$_GET["name"];
$sql = $dbConnection->prepare('SELECT 'coordinates', 'center' , 'content_string' FROM Regions WHERE `id` = ?');
$sql->bind_param('i', $value);
$sql->execute();
$sql->bind_result($coordinates, $center, $content_string)
while($sql->fetch())
{
echo $coordinates;
echo $center;
echo $content_string;
}
Prepared statement with MySQLi
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);
// set parameters and execute
$username= "John";
$email = "john#example.com";
$stmt->execute();
$username= "Mary";
$email = "mary#example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
Php tips and tricks.
http://www.phptherightway.com/
If you are concerned about security this is the topic that I love very much.
What are the best PHP input sanitizing functions?.

mysql result into php array

I'm trying to convert the result that i'm getting from mysql to a php array
can anyone helps me
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "women";
$conn = new mysqli($servername, $username, $password, $dbname);
$id=$_GET['id'];
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS,
DAY(ADDDATE(ADDDATE(`dateDebutC`, `dureeC`),`dureeR`))AS DAYS
FROM normalW
where id = '$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
foreach($new_array as $array){
echo $row['DAYS'].'<br />';
echo $row['MONTHS'].'<br />';
}
} else {
echo "0 results";
}
$conn->close();
?>
Problem solved Thank you guys
To answer your question you must first declare the new array
$new_array = array();
Then loop through your query results to populated the array
while ($row = $result->fetch()) {
$new_array[] = $row;
}
But as one of the comments mentioned you really should be using prepared statements to protect yourself from sql injection.
$stmt = $mysqli->prepare("SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS, DAY(ADDDATE(ADDDATE(`dateDebutC`, `dureeC`),`dureeR`)) AS DAYS FROM normalW where id = ?");
/* bind parameters i means integer type */
$stmt->bind_param("i", $id);
$stmt->execute();
$new_array = array();
while($row = $stmt->fetch()) {
$new_array[] = $row;
}

Categories