PHP database SQL insert - php

I am trying to write data form mine app to a external database.
I just get no response form my PHP page. When I look at the variables that I send to the PHP page, they are received good and nothing goes wrong at that moment.
But when I do an INSERT with SQL it goes wrong. (I think).
When I go to mine PHPadmin page and I do next SQL command, it works:
INSERT INTO images (FBid,Datum,Lat,Longi,Image)
VALUES ('1846465164',
'2016-08-25 14:14:15',10.5,5.69,'/9j/
4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE
BAQEBQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB')
So i have next database;
ID(PRIMARY KEY AUTOINCREMENT),
FBid (varchar(255)),
Datum (datetime),
Lat (Double),
Longi(Double),
Image(Blob).
And this is my php page:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
define('HOST','localhost');
define('USER','XXXXXXXXX');
define('PASS','XXXXXXXXX');
define('DB','database2');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
$image = $_POST['image'];
$FBid = $_POST['FBid'];
$date = $_POST['Date'];
$long = $_POST['long'];
$lat = $_POST['lat'];
$stmt = $con->prepare(
"INSERT INTO images (FBid,Datum,Lat,Longi,Image)
VALUES (:Fbid,:date,:lat,:long,:image)");
$stmt->bindParam(":Fbid",$FBid);
$stmt->bindParam(":date", $date);
$stmt->bindParam(":lat", $lat);
$stmt->bindParam(":long", $long);
$stmt->bindParam(":image","s",$image);
$stmt->execute();
$check = mysqli_stmt_affected_rows($stmt);
if($check == 1){
echo "Image Uploaded Successfully";
}else{
echo "Error Uploading Image";
}
mysqli_close($con);
}else{
echo "Error";
}
Thank you guys!
Regards,
Stijn

Looking at the database connection, you are using mysqli prepare wrongly. In the INSERT statement, it looks like a PDO version. If you want to use PDO version, have a look at this link. You can't mix PDO and mysqli. The procedural style for mysqli_prepare is like below:
$stmt = mysqli_prepare($con, "INSERT INTO images VALUES (?, ?, ?, ?, ?)");
if ( !$stmt ) {
die('mysqli error: '.mysqli_error($con);
}
mysqli_stmt_bind_param($stmt, 'ssddb', $FBid,$date,$lat,$long,$image);
if ( !mysqli_stmt_execute($stmt)) {
die( 'stmt error: '.mysqli_stmt_error($stmt) );
}
$check = mysqli_stmt_affected_rows($stmt);
if($check == 1){
echo 'Image successfully uploaded';
}else{
echo 'Error uploading image';
}
mysqli_stmt_close($stmt);

Related

PHP mutiple queries no result in database

I'm working on an android app that requires connection to a database. I have the android part working but I'm having trouble with my php script.
<?php
$con = mysqli_connect(/This info is correct/) or die ("Unable to connect");
$gebruikersnaamOntvanger = $_POST["gebruikersnaamOntvanger"];
$idBetaler = $_POST["idBetaler"];
$bedrag = $_POST["bedrag"];
$saldoBetaler = $_POST["saldo"];
$response = array();
$response["success"] = "false";
$statement = mysqli_prepare($con, "SELECT idGebruiker, Saldo FROM Gebruikers WHERE Gebruikersnaam = ?");
mysqli_stmt_bind_param($statement, "s", $gebruikersnaamOntvanger);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $idGebruiker, $Saldo);
while($row = mysqli_stmt_fetch($statement)){
$idOntvanger = $idGebruiker;
$saldoOntvanger = $Saldo;
}
$saldoOntvanger += $bedrag;
$saldoBetaler -= $bedrag;
try {
$statement2 = mysqli_prepare($con, "INSERT INTO Transacties (idBetaler, idOntvanger, Bedrag, Datum, Uitgevoerd) VALUES(?, ?, ?, now(), 1)");
mysqli_stmt_bind_param($statement2, "iid", $idBetaler, $idOntvanger, $bedrag);
mysqli_stmt_execute($statement2);
$response["success"] = "success";
} catch(Exception $e) {
$response["success"] = $e->gettext;
}
echo json_encode($response);
?>
So the android part work and returns the JSON object correctly but nothing changes in the database. I have tried adding a try catch so I get what's the error but the try catch never works. The script alwayws returns success even if it didn't work. Please be aware I'm new to PHP and I have double checked the SQL queries and they should be correct. If you need more information please ask.
mysqli_* function dosn't throws exceptions. So your catch is never executed even on error. Change your code like this :
if(!mysqli_stmt_execute($statement2))
throw new Exception(mysqli_stmt_error($statement2));
When you'll see the error you can fix your code. May be add same error handling to mysqli_prepare and others
I think the issue was the use of iid in the binding for the insert query. It should either be iis or iii presumably. You tried using try/catch blocks but to my mind did not make full use of them - the creation of a prepared statement should be tested to see if it succeeds or fails ~ the outcome of which can be used in the try/catch logic to indicate faults. Excuse the mix of procedural and OOP style code
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST["gebruikersnaamOntvanger"], $_POST["idBetaler"], $_POST["bedrag"], $_POST["saldo"] ) ){
try{
$con = mysqli_connect(/This info is correct/) or die ("Unable to connect");
$gebruikersnaamOntvanger = $_POST["gebruikersnaamOntvanger"];
$idBetaler = $_POST["idBetaler"];
$bedrag = $_POST["bedrag"];
$saldoBetaler = $_POST["saldo"];
$response = array('success'=>false);
$stmt=$conn->prepare( 'select `idgebruiker`, `saldo` from `gebruikers` where `gebruikersnaam` = ?' );
if( !$stmt ) throw new Exception('unable to prepare select query');
else {
$stmt->bind_param( 's', $gebruikersnaamOntvanger );
$result=$stmt->execute();
if( !$result )throw new Exception('No results from select query');
else {
$stmt->store_result();
$stmt->bind_result( $idGebruiker, $Saldo );
while( $stmt->fetch() ){
$idOntvanger = $idGebruiker;
$saldoOntvanger = $Saldo;
}
$saldoOntvanger += $bedrag;
$saldoBetaler -= $bedrag;
$stmt=$con->prepare('insert into `transacties` ( `idbetaler`, `idontvanger`, `bedrag`, `datum`, `uitgevoerd` ) values(?, ?, ?, now(), 1)');
if( !$stmt )throw new Exception('Unable to prepare insert query');
else {
/* What is the value of $bedrag? integer, string?? */
/*
The binding iid was incorrect - perhaps iis or iii
*/
$stmt->bind_param('iis', $idBetaler, $idOntvanger, $bedrag );
$result = $stmt->execute();
$response['success']=$result;
}
}
}
echo json_encode( $response );
}catch( Exception $e ){
echo $e->getMessage();
}
}
?>

inserting multiple rows in mysql from json string/array using php?

"i am trying to develop an script which allows me to insert multiple rows from an jsonarray in mysql database, but upon testing only one rows is being inserted and here is my code:
<?php
$con = mysqli_connect($host,$user,$password,$database) or die('Unable to Connect');
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$jsonData=file_get_contents("sampledata.json");
$jsonString=json_decode($jsonData,true);
foreach($jsonString['Order Summary'] as $cart)
{
$name=$cart['ProductName'];
$price=$cart['ProductPrice'];
$quantity=$cart['ProductQuantity'];
$cost=$cart['ProductCost'];
$seller=$cart['SellerId'];
$stmt=$con->prepare("INSERT INTO sProducts(Name,Price,Quantity,Cost,Sellerid)VALUES(?,?,?,?,?)");
$stmt->bind_param("sssss",$name,$price,$quantity,$cost,$seller);
if($stmt->execute())
return json_encode("data inserted");
return json_encode("error");
}
}
can anyone tell me where is the mistake or could guide me into this direction ?
For one, you are reutrning in the first iteration of the loop - which means that the script stops. return should only be used to return from a function.
If you remove both returns, that will make the loop continue until its done.
And you should not prepare the query inside the loop, its not needed - and much more efficient to prepare it before you start looping (it can be used multiple times with different values when you bind and execute in a loop). I've also added some spaces in the code to make it easier to read
$con = mysqli_connect($host,$user,$password,$database) or die('Unable to Connect');
$msg = "data inserted";
if ($_SERVER["REQUEST_METHOD"]=="POST") {
$jsonData = file_get_contents("sampledata.json");
$jsonString = json_decode($jsonData,true);
$stmt = $con->prepare("INSERT INTO sProducts (Name, Price, Quantity, Cost, Sellerid) VALUES (?, ?, ?, ?, ?)");
foreach($jsonString['Order Summary'] as $cart) {
$name = $cart['ProductName'];
$price = $cart['ProductPrice'];
$quantity = $cart['ProductQuantity'];
$cost = $cart['ProductCost'];
$seller = $cart['SellerId'];
$stmt->bind_param("sssss", $name, $price, $quantity, $cost, $seller);
if (!$stmt->execute())
$msg = "Something went wrong";
}
}
return json_encode($msg);

php- inserting data into the database

I am a beginner when we talk about PHP. SO I have no idea where I made a mistake using PHP.
<?php
require "conn.php";
$name = "yolo";
$surname = "yolo";
$nameOfFee= "asd";
$date = '2012-08-06';
$mysql_query = "(INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee)
SELECT Person.ID,Fee.ID,'$date'
FROM Person,Fee
WHERE Person.Name = '$name' AND Person.Surname = '$surname' AND Fee.Name_of_fee = '$nameOfFee');";
if($conn->query($mysql_query) === TRUE){
echo "Insert completed";
}
else{
echo "Insert not completed";
}
$conn->close();
?>
It always puts that Insert is not complete...
The Problems
There are a few syntax errors in this piece of code you have provided:
// here it starts, what is this "(" for before insert?
// Take note that your query is vulnerable to SQL attacks
$mysql_query = "(INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee)
SELECT Person.ID,Fee.ID,'$date'
FROM Person,Fee
WHERE Person.Name = '$name' AND Person.Surname = '$surname' AND Fee.Name_of_fee = '$nameOfFee');";
How to fix it
To fix these things I recommend you use the MySQLi OOP, like you are using now, but add prepared statements. I will walk through the new code with you so you can understand the process.
require "conn.php";
$name = "yolo";
$surname = "yolo";
$nameOfFee= "asd";
$date = '2012-08-06';
$sql = "INSERT INTO Relation (Person_ID, Fee_ID, Date_of_fee) VALUES (?, ?, ?)"; // rewrite your query with a preset number of values to prevent SQL Attacks
if($stmt = $conn->prepare( $sql ))
{ // before we run check to make sure the query worked
$stmt->bind_param('sss', $name, $nameOfFee, $date); // bind your variables so to know what goes where
$stmt->execute(); // execute the query
$stmt->close(); // close connection for safety
// message as an array for the user as feedback.
$message = array(
'is_error' => 'success',
'message' => 'Record was entered into database.'
);
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Query Error, please revise the information.'
);
}

php script wont add record to mysql

The first example will add data to mysql database without any issue. The second block of code - where I try to use variables wont. Can someone please explain where I am going wrong?
<?php
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES ('Edit me',4,1)";
$result = mysqli_query($connection, $query);
Problem CODE:
<?php
$menu_name = "TEST";
$position = 5;
$visible = 1;
$query = "INSERT INTO subjects (menu_name,position,visible)
VALUES ('{menu_name}',{position}, {visible})";
$result = mysqli_query($connection, $query);
*Answer updated with MySQLi prepare statement, thanks #h2ooooooo
<?php
//Open a new connection to the MySQL server
$db = new mysqli('host','username','password','database_name');
//Output connection errors
if ($db->connect_error) {
die('Error : ('. $db->connect_errno .') '. $db->connect_error);
}
$sql = "INSERT INTO subjects (menu_name, position, visible) VALUES (?, ?, ?)";
if (!$stmt = $db->prepare($sql)) {
echo 'Database prepare error';
exit;
}
$stmt->bind_param('sss', $menu_name, $position, $visible);
if (!$stmt->execute()) {
echo 'Database execute error';
exit;
}
$stmt->close();
I'd say for you to take a look in the many tutorials thorugh net, like these:
http://markonphp.com/simple-insert-mysqli/ and
http://www.sanwebe.com/2013/03/basic-php-mysqli-usage
$query = "INSERT INTO subjects (menu_name,position,visible) VALUES
('".$menu_name."','".$position."', '".$visible."')";
try this

skip stmt block

I am brand new to php and I ran into a problem that has already taken a few hours of poking around and researching and I could not find anything like it anywhere around the net.
Database:MyPHPAdmin winserver
Goal: Create a new row in table 'photo'. Take the last insert p_id for the current user and update the table accessible_to by creating a new row with that p_id.
I know I can create a trigger, and no it does not work either don't know why. Run out of ideas how.
What I found out by simply printing before-in-after the if statement
if ($stmt = $mysqli->prepare("insert into accessible_to values(?, ?, ?)"))
is that it just bypasses it.
Please post your suggestions.
P.S. The if statement above to which I am referring has been twisted in several ways and yet it does not work.
The connection is already imported.
Thank you a lot.
if(!isset($_SESSION["id"])) {
echo "You are not logged in. ";
echo "You will be returned to the homepage in 3 seconds or click here.\n";
header("refresh: 3; index.php");
}
else {
//if the user have uploaded a photo, insert it into database
if(isset($_POST["ext"])) {
//insert into database, note that p_id is auto_increment
if ($stmt = $mysqli->prepare("insert into photo (ext, owner_id) values (?,?)")) {
$stmt->bind_param("ss", $_POST["ext"], $_SESSION["id"]);
$stmt->execute();
$stmt->close();
$id = htmlspecialchars($_SESSION["id"]);
}
//The following function is fetching the last added p_id in PHOTO by the user with the current SESSION
//Do not simply get the last p_id in PHOTO because someone else might have just added another picture meanwhile
if ($stmt = $mysqli->prepare("select MAX(p_id) from photo where owner_id = ?")){
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($p_id);
if ($stmt->fetch()){
$p_id = htmlspecialchars($p_id);
}
}
echo "BEFORE accessible_to insertion";
echo '<br />';
if ($stmt = $mysqli->prepare("insert into accessible_to values(?, ?, ?)")){
echo "Finally inside accessible_to insertion";
echo '<br />';
$stmt->bind_param("iss", $p_id, $id, 'T');
$stmt->execute();
$stmt->close();
}
echo "AFTER accessible_to insertion";
echo '<br />';
}
//if not then display the form for posting message
else {
echo "Something";
You can't boolean test an assignment and expect it to return a different result. What you want to test for is if $stmt->execute successfully executed or not.
$stmt = $mysql->prepare("insert into foo values (?,?)");
$stmt->bind_param(1,$f1);
$stmt->bind_param(2,$f2);
if ($stmt->execute()) {
... worked
} else {
... fubar
}
You have to start by calling mysqli::connect($server, $user, $pw, $db). The best way to do that is by constructing an object like:
$connection = new mysqli($server, $user, $password, $db);
if ($connection->errno)
{
echo "Connection failed";
echo $this->connection->error;
}
else
{
$stmt = $connection->prepare("insert into photo (ext, owner_id) values (?,?)")) {
$stmt->bind_param("ss", $_POST["ext"], $_SESSION["id"]);
$stmt->execute();
$stmt->close();
}

Categories