"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);
Related
This code works if i run in a browser. When i run the script via a cron, it doesn't get through the array and stops halfway? Why is this?
$url_array = array("eur-gbp","eur-aud","usd-chf","eur-usd","eur-jpy","gbp-jpy","eur-cad","eur-chf","usd-cad","usd-jpy","cad-chf","cad-jpy","gbp-usd","aud-usd","gbp-chf","chf-jpy","gbp-cad","aud-cad","aud-chf","aud-jpy","aud-nzd","eur-nzd","gbp-aud","gbp-nzd","nzd-chf","nzd-usd","nzd-cad","nzd-jpy");
$option_array = array(1,2,3,4,5,6,7);
$type_array = array(1,2,3,4,5,6);
foreach($url_array as $url_type) {
//code
foreach($option_array as $option) {
//code
foreach($duration_array as $duration) {
//code
foreach($type_array as $type) {
//mysql insert
$sql = "SELECT * FROM `data_analysis` WHERE date_time='".$date."' AND type='".$url_type."' LIMIT 1";
$query = $this->db->query($sql);
$result = $query->fetch_assoc();
if($result){
$sql = "UPDATE `data_analysis` SET value='".$percentage."', price_change='".$price."', parent='1' WHERE date_time='".$date."' AND type='".$url_type."'";
} else {
$sql = "INSERT IGNORE INTO `data_analysis` (date_time,value,price_change,type,parent) VALUES ('".$date."','".$percentage."','".$price."','".$url_type."','1')";
}
}
}
}
}
This isn't the exact code as it is too long to post but similar. The code works perfectly in the browser?? running via cron it stops at gbp-jpy? Why is this?
Is there a mysql query limit?
Add a unique index on (type, date_time) to the table. Then combine your two queries into 1. Also, use a prepared statement.
$stmt = $this->db->prepare("
INSERT INTO data_analysis (date_time, value, price_change, type, parent)
VALUES (?, ?, ?, ?, '1')
ON DUPLICATE KEY UPDATE value = VALUES(value), price_change = VALUES(price_change), parent = VALUES(parent)");
$stmt->bind_param("ssss", $date, $percentage, $price, $url_type);
foreach($url_array as $url_type) {
//code
foreach($option_array as $option) {
//code
foreach($duration_array as $duration) {
//code
foreach($type_array as $type) {
//mysql insert
$stmt->execute();
}
}
}
}
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);
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
I have a basic question asking how to use the isset(); command and how it should be written in the example below. I am trying to insert values into query, then retrive the last ImageId inserted and insert that into another table
session_start();
$imagesql = "INSERT INTO Image (ImageFile)
VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$img);
//Assign the variable
$img = 'ImageFiles/'.$_FILES['fileImage']['name'];
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
$lastImageID = $mysqli->insert_id;
$_SESSION['lastImageID'] = $lastImageID;
$imagequestionsql = "INSERT INTO Image_Question (ImageId, SessionId, QuestionId)
VALUES (?, ?, ?)";
if (!$insertimagequestion = $mysqli->prepare($imagequestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err imagequestion";
}
$qnum = (int)$_POST['numimage'];
$insertimagequestion->bind_param("iii",$lastImageID, $sessionid, $qnum);
$insertimagequestion->execute();
if ($insertimagequestion->errno) {
// Handle query error here
}
$insertimagequestion->close();
Not exactly sure what your asking for, but guessing wildly:
session_start();
...... //PDO code and commands
$lastImageID = $mysqli->insert_id;
$_SESSION['lastImageID'] = $lastImageID;
if (isset($_SESSION['lastImageID'])) {
// do this
} else {
// do that
}
You only need to call isset if you are reading a variable that may not be defined.
In this situation, you are writing to $_SESSION['lastImageID'], so you don't need to check.
An example of where isset would be needed:
if (isset($_SESSION['lastImageID']))
{
$lastImageID = $_SESSION['lastImageID'];
}
else
{
$lastImageID = get_this_from_db_or_something();
}
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();
}