skip stmt block - php

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();
}

Related

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);

beginTransaction in PDO

I've recently started learning about PDO.
My question is how can i execute more than 1 prepared statement.
In my example i'm trying to add a new student to the database.
The first part of the code i'm adding the student into the 'students' table.
The second part of the code i'm trying to add all of his classes (from array e.g an array(PHP,JAVA,ANGULAR)) into student_class table (which contain 2 columns - student_id and class_id).
Here's a snippet of what i've tried:
function addStudent($name, $phone, $email, $classes){
global $conn;
//first part
$stat = $conn->prepare("INSERT INTO students (sName, phone, email) VALUES(:name, :phone, :email)");
$stat->bindValue("name",$name,PDO::PARAM_STR);
$stat->bindValue("phone",$phone,PDO::PARAM_STR);
$stat->bindValue("email",$email,PDO::PARAM_STR);
$stat->execute();
//second part
//insert classes into student_class
$lastId = $conn->lastInsertId();
$conn->beginTransaction();
$len = count($classes);
for ($i=0; $i < $len; $i++) {
$cid = getClassByName($classes[$i]);//returns the class id
$cl = $conn->prepare("INSERT INTO student_class (student_id,class_id) VALUES(:sid, :cid)");
$cl->bindValue("sid",$lastId,PDO::PARAM_INT);
$cl->bindValue("cid",$cid,PDO::PARAM_INT);
$cl->execute();
}
$conn->commit();
}
try{
addStudent($params['name'], $params['phone'], $params['email'], $params['classes']);
}
catch(PDOException $e){
echo $e->getMessage();
$conn->rollback();
}
The result of this is: the user gets added to the 'students' table but the classes remain untouched (i'm getting no error), so i guess i'm doing something wrong with the second part.
I hope you can shed some light on this matter.
If these are prepared statements then you only "create" them once, and can execute them multiple times. Also edited your code to print error information, use it to debug.
function addStudent($name, $phone, $email, $classes){
global $conn;
//first part
$stat = $conn->prepare("INSERT INTO students (sName, phone, email) VALUES(:name, :phone, :email)");
$stat->bindValue("name",$name,PDO::PARAM_STR);
$stat->bindValue("phone",$phone,PDO::PARAM_STR);
$stat->bindValue("email",$email,PDO::PARAM_STR);
$stat->execute();
//second part
//insert classes into student_class
$lastId = $conn->lastInsertId();
$conn->beginTransaction();
$len = count($classes);
$cl = $conn->prepare("INSERT INTO student_class (student_id,class_id) VALUES(:sid, :cid)");
if (!$cl) {
echo "\nPDO::errorInfo():\n";
print_r($conn->errorInfo());
}
for ($i=0; $i < $len; $i++) {
$cid = getClassByName($classes[$i]);//returns the class id
$cl->bindValue("sid",$lastId,PDO::PARAM_INT);
$cl->bindValue("cid",$cid,PDO::PARAM_INT);
$cl->execute();
echo "\nPDOStatement::errorInfo():\n";
$arr = $cl->errorInfo();
print_r($arr);
}
$conn->commit();
}
try{
addStudent($params['name'], $params['phone'], $params['email'], $params['classes']);
}
catch(PDOException $e){
echo $e->getMessage();
$conn->rollback();
}

PHP database SQL insert

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);

getting error for mysql when i am using if else in there

getting error for mysql when i am using if else in there. i dont know what should i do and when i am using duplicate condition to update then it not woring i am not be able to find where is error
this is the error which is i am getting.
ERROR:SQLSTATE[HY093]: Invalid parameter number: parameter was not
defined
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt=$conn->prepare("SELECT uniqueid FROM hotelcarttemp WHERE uniqueid=:uniqueid");
$stmt->execute(array(':uniqueid'=>$uniqueid));
$count=$stmt1->rowCount();
echo "count-".$count;
if($count>0)
{
$sql = "UPDATE hotelcarttemp SET `hotelname`='".$hotelname."',`roomtype`='".$roomtype."',`checkin`='".$checkin."',`checkout`='".$checkout."',`Country`='".$Country."',`Destination`='".$Destination."',`price`='".$price."' WHERE uniqueid='".$uniqueid."'";
echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
else
{
$sql = "INSERT INTO hotelcarttemp (timestamp, packageid, uniqueid, hotelname, roomtype, checkin, checkout, Country, Destination, hoteldetail, price)
VALUES ('"
.$timestamp."','"
.$packageid."','"
.$uniqueid."','"
.$hotelname."','"
.$roomtype."','"
.$checkin."','"
.$checkout."','"
.$Country."','"
.$Destination."','"
.addslashes($hoteldetail)."','"
.$price."'
)";
// echo "sql- ".print_r($sql);
$stmt = $conn->prepare($sql);
// echo print_r($stmt);
$stmt->execute();
}
}
catch(PDOException $e) {
echo 'ERROR:' . $e->getMessage();
} here
Your SELECT query where condition is WHERE uniqueid=:uniqueid
And you are binding username to it
$stmt->execute(array(':username'=>$uniqueid));//:username invalid parameter
Change this to
$stmt->execute(array(':uniqueid'=>$uniqueid));

check if user exists with php and mysql stmt

I'm creating an authentification file with php and mysql, but I have this mistake in this line:
$stmt2->bind_param('ss',$twitter_id, $name);
The error message is
Call to a member function bind_param() on a non-object in ...
Where's my mistake?
$name in my database is a VARCHAR
$twitter_id in my database is a VARCHAR
$bd is my database connection
If a user is already registered, it should show me a message saying "User already registered", and if the user isn't registered, it should insert a new id and name in my database.
session_start();
if (!isset($_SESSION['userdata'])) {
header("location: index.php");
} else {
$userdata = $_SESSION['userdata'];
$name = $userdata->name;
$twitter_id = $userdata->id;
$stmt = $bd->prepare("SELECT ID_TWITTER FROM USERS");
$stmt->execute();
$stmt->bind_result($checkUser);
if ($stmt->fetch()) {
if($checkUser!==$twitter_id){
$cSQL = "INSERT INTO USERS (ID_TWITTER, FULL_NAME) VALUES(?,?)";
$stmt2 = $bd->prepare($cSQL);
$stmt2->bind_param('ss',$twitter_id, $name);
$stmt2->execute();
$stmt2->close();
} else {
echo "User already exits";
}
}
$stmt->close();
}
Could it be a typo? does $bd exist or should it be $db ?
Shameless plug: I do this exact thing in a project I have on github. Feel free to use the classes for whatever you like; they are mostly copy-pastable.
Your real issue is that $bd->prepare() returned false.
Check that you actually called it correctly and set it to new mysqli(*params)
The error Call to a member function ... on a non-object in ... means that $db is not an object, which means that it was not instantiated to an object. Thus, $this->method() isn't possible. bind_param(string $format, mixed &*vars); uses pass-by-reference and if this fails, it throws an error.
Try it yourself by sticking this in there:
$stmt->bind_param("ss", "string", "string");
To get around this issue where it can fail, check if $db->prepare() returns true:
if ($query = $bd->prepare($sql)) {
//stuff
}
In addition, in the first query you do it is probably not a good idea to be adding the overhead of a prepare for a single query that only checks row count without user input.
Solved : it works now
$stmt = $bd->prepare("SELECT ID_PROVIDER FROM USERS WHERE ID_PROVIDER = ?");
$stmt->bind_param('s', $twitter_id);
$stmt->execute();
$stmt->bind_result($checkUser);
while ($stmt->fetch()) {
$result = $checkUser;
}
if (empty($result)) {
$cSQL = "INSERT INTO USERS (ID_TWITTER, FULL_NAME)
VALUES(?,?)";
$stmt2 = $bd->prepare($cSQL);
$stmt2->bind_param('ss', $twitter_id, $name);
$stmt2->execute();
$stmt2->close();
}else {
echo "User already exits";
}

Categories