SQL Update table (Azure with PHP) - php

somehow i must make a mistake somewhere and can't seem to find the correct solution, must be doing something wrong. I want to update my Azure SQL table called Celebrity from a PHP page and it doesn't update. Can you pls help me or tell me what i am doing wrong
<?php
try {
$conn = new PDO( "sqlsrv:Server= $host ; Database = $db ", $user, $pwd);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(Exception $e){
die(var_dump($e));
}
if(!empty($_POST)) {
try {
$FirstName = $_POST['FirstName'];
$LastName = $_POST['LastName'];
$id = $_POST['id_celebrity'];
$sql_update = "UPDATE
Celebrity
SET
(FirstName, LastName)
VALUES
(?,?)
WHERE
id_celebrity='$id'";
$stmt = $conn->prepare($sql_update);
$stmt->bindValue(1, $FirstName);
$stmt->bindValue(2, $LastName);
$stmt->execute();
}
catch(Exception $e) {
die(var_dump($e));
}
echo "Celebrity Updated in DB!";
}
?>
Here is the instruction in use and this is what i get back from the AZURE server:
object(PDOException)#3 (8) { ["message":protected]=> string(97) "SQLSTATE[42000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near '('." ["string":"Exception":private]=> string(0) "" ["code":protected]=> string(5) "42000" ["file":protected]=> string(62) "D:\home\site\wwwroot\CelebrityOverview\CelebrityEditResult.php" ["line":protected]=> int(57) ["trace":"Exception":private]=> array(1) { [0]=> array(6) { ["file"]=> string(62) "D:\home\site\wwwroot\CelebrityOverview\CelebrityEditResult.php" ["line"]=> int(57) ["function"]=> string(7) "execute" ["class"]=> string(12) "PDOStatement" ["type"]=> string(2) "->" ["args"]=> array(0) { } } } ["previous":"Exception":private]=> NULL ["errorInfo"]=> array(3) { [0]=> string(5) "42000" [1]=> int(102) [2]=> string(80) "[Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near '('." } }

Try this instead:
$sql_update = "UPDATE Celebrity
SET FirstName = ?, LastName = ?
WHERE id_celebrity='$id'";
Assigning each column a value with a comma in between, UPDATE markup is not same as INSERT.

Related

I have a php array I'm trying to insert into a database, but the content that gets inserted just says "Array"

As the description says, I'm attempting to send a php array into a database, I know that mysql doesn't understand php so I was wondering how I get the content out of the php array in order to insert it. Right now I have several columns for said table in the database, but would it be easier to insert the data as one big string rather than individually?
Insert.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "salestest";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
var_dump($_POST);
$name = $conn -> real_escape_string($_POST['txtCustomerNameLater']);
$phone = $_POST['txtPhoneLater'];
$email = $_POST['txtEmailLater'];
$ropo = $_POST['txtRopoLater'];
$address = $_POST['txtAddressLater'];
$sku = $_POST['txtSKULater'];
$productName = $_POST['txtProductNameLater'];
$quantity = $_POST['txtQuantityLater'];
$retailPrice = $_POST['txtRetailPriceLater'];
$listPvrice = $_POST['txtListPrice555Later'];
$total = $_POST['txtTotalLater'];
$alueCookie = array_values($_COOKIE);
$firstValCookie = $valueCookie[0];
$date = date('Y-m-d H:i:s', time());
$counts = $sku;
foreach($counts as $index=>$dat){
$stmt = $conn->prepare("INSERT INTO orders(customer_name, phone, email, ropo, address,
sku, product_name, quantity, retail_price, list_price, total,timestamp, user)
values(?,?,?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("sssssssssssss", $name, $phone, $email, $ropo, $address, $sku, $productName,
$quantity, $retailPrice, $listPrice, $total, $date, $firstValCookie);
$stmt->execute();
$stmt->close();
}
$conn->close();
?>
Array of data to insert:
array(11) { ["txtCustomerNameLater"]=> string(13) "101 Auto Body" ["txtPhoneLater"]=> string(12)
"510-524-4857" ["txtEmailLater"]=> string(20) "henrykseng#yahoo.com" ["txtRopoLater"]=> string(4)
"asdf" ["txtAddressLater"]=> string(55) "101 Auto Body 5327 Jacuzzi St Ste 3A Richmond, CA 94804"
["txtTotalLater"]=> string(5) "52.84" ["txtSKULater"]=> array(2) { [0]=> string(13) "8620843-0423L"
[1]=> string(14) "15952187-0053L" } ["txtRetailPriceLater"]=> array(2) { [0]=> string(5) "11.75"
[1]=> string(5) "66.81" } ["txtListPrice555Later"]=> array(2) { [0]=> string(4) "7.75" [1]=>
string(5) "45.09" } ["txtProductNameLater"]=> array(2) { [0]=> string(44) "Stone Guard Left Volvo XC
90 03-14 Rear Door" [1]=> string(34) "Stone Guard Chev/Gmc 3500 DRW Left" } ["submitOrder1"]=>
string(0) "" }
The customer's information goes in as normal, but the product details only say "array" for each column and it's doing an insert for each item in the array, I send out a confirmation email for this product, and i'm not sure how I would catch each insert for the email.

Using PHP / MySQLi to loop through json_decoded array not working for Update query

I am using json_decode() to decode an Ajax result which returns the below array (shortened example).
Now I want to loop through this area and to update the rId for each vId as per the values from the array but this part does not work.
Can someone show me how to do the loop part correctly here (the query itself should be ok) ?
My array:
array(3) {
[0]=>
array(2) {
["vId"]=>
string(8) "04567901"
["rId"]=>
string(6) "DE-003"
}
[1]=>
array(2) {
["vId"]=>
string(8) "04567902"
["rId"]=>
string(6) "DE-008"
}
[2]=>
array(2) {
["vId"]=>
string(8) "04567903"
["rId"]=>
string(6) "DE-009"
}
}
My PHP / MySQLi:
$postData = $_POST;
$transferData = $_POST['transferData'];
$json = json_decode($transferData, true);
$conn = new mysqli($host, $username, $password, $database);
if($conn->connect_error) {
die("Connection Error: " . $conn->connect_error);
}
$stmt = $conn->prepare("UPDATE locations l SET l.rId = ? WHERE l.vId = ?");
foreach($json as $vId => $rId) {
$stmt->bind_param('ss', $rId, $vId);
$stmt->execute();
}
$stmt->close();
$conn->close();
In your foreach, the key refers to the index of the array rather than what you consider the key to be. The keys in your case are actually 0, 1, 2, [...].
You return an array of arrays, so get the parts you want as follows:
foreach($json as $key => $value) {
$stmt->bind_param('ss', $value['rId'], $value['vId']);
$stmt->execute();
}

PHP mysqli executes thousands of queries on fetch()

I'm trying to figure a mysqli DB connection in PHP. The problem is everytime I try to fetch the result, literally thousands of queries are executed, and MySQL server and/or browser dies.
Here is the code I use:
$resultQuery = $this->db->prepare($query_id);
var_dump($this->db);
var_dump($resultQuery);
$resultQuery->execute();
//$result = $resultQuery->dbStatement->fetch();
$resultQuery->close();
return $result;
If I uncomment the row with the fetch method, everything goes nuts...
Here is the result of var_dumb's used in the code above:
query:
string(69) " SELECT userid, fname, lname FROM users WHERE finished=0 "
db object:
object(mysqli)#2 (17) {
["affected_rows"]=>
int(-1)
["client_info"]=>
string(6) "5.1.49"
["client_version"]=>
int(50149)
["connect_errno"]=>
int(0)
["connect_error"]=>
NULL
["errno"]=>
int(0)
["error"]=>
string(0) ""
["field_count"]=>
int(0)
["host_info"]=>
string(25) "Localhost via UNIX socket"
["info"]=>
NULL
["insert_id"]=>
int(0)
["server_info"]=>
string(17) "5.1.66-0+squeeze1"
["server_version"]=>
int(50166)
["sqlstate"]=>
string(5) "00000"
["protocol_version"]=>
int(10)
["thread_id"]=>
int(2220)
["warning_count"]=>
int(0)
}
response before fetch():
object(mysqli_stmt)#47 (9) {
["affected_rows"]=>
int(0)
["insert_id"]=>
int(0)
["num_rows"]=>
int(0)
["param_count"]=>
int(0)
["field_count"]=>
int(3)
["errno"]=>
int(0)
["error"]=>
string(0) ""
["sqlstate"]=>
string(5) "00000"
["id"]=>
int(1)
}
Here is how I connect to my DB:
if ($this->persistency)
{
$this->db = new mysqli("p:" . $this->server, $this->user, $this->password);
}
else
{
$this->db = new mysqli($this->server, $this->user, $this->password);
}
$this->db->query("SET CHARACTER SET utf8") or die("Error during character set initialization | " . mysql_error());
$this->db->query("SET NAMES 'utf8'") or die("Error during character set names initialization | " . mysql_error());
if (!$this->db->connect_error)
{
if ($database != "")
{
$this->dbname = $database;
$dbselect = $this->db->select_db($this->dbname);
if (!$dbselect)
{
$this->db->close($this->db);
$this->dbError = "Error choosing database!";
}
else
{
$this->dbResults = new mysqli_result();
$this->dbStatement = new mysqli_stmt();
return $this->dbError = false;
}
}
}
else
{
return $this->dbError = $this->db->connect_error;
}
It seems like mysqli can't decide when to stop sending queries to be fetched...
What am I doing wrong? Can someone help me?
Are you binding your results to a var? You are using mysqli::prepare but I don't see the result of the select binded to any variables:
http://php.net/manual/en/mysqli-stmt.bind-result.php

passing user object to function and then to prepared stament (PHP)

I'm fairly new to PHP, and I'm working with mysqli, OOP and prepared statements.
My question is this:
I'm trying to pass an user(object) to an Insert_user(func) in my database(class).
I have 3 classes, 'logic', 'data' and 'index'. Index includes data and logic, and initiates
the connection and user.
In my function (insert_user), I'm using an array to pass user variables into, before
binding and executing my statement.
Hers is my code:
<?php
function insert_user($user) {
$query = "INSERT INTO user VALUES (?,?,?,?,?,?,?,?,?,?)";
$binding = 'issssiisss';
$variables = array( $user->user_id, $user->f_name, $user->l_name, $user->address, $user->city, $user->zipcode, $user->mobile_number, $user->mail, $user->pass_key, $user->pass_word);
$stmt = $this->mysqli->prepare($query);
$stmt->bind_param($binding,$variables[0],$variables[1],$variables[2],$variables[3],$variables[4],$variables[5],$variables[6],$variables[7],$variables[8],$variables[9]);
$stmt->execute();
}
?>
Here is my var_dump from browser:
object(user)#1 (10) { ["user_id"]=> int(1) ["f_name"]=> string(5) "pelle" ["l_name"]=> string(5) "kanin" ["address"]=> string(7) "vænget" ["city"]=> string(6) "aaaaaa" ["zipcode"]=> int(123) ["mobile_number"]=> int(123) ["mail"]=> string(4) "fedt" ["pass_key"]=> string(3) "ert" ["pass_word"]=> string(4) "erto" }
string(10) "issssiisss"
array(10) { [0]=> int(1) [1]=> string(5) "pelle" [2]=> string(5) "kanin" [3]=> string(7) "vænget" [4]=> string(6) "aaaaaa" [5]=> int(123) [6]=> int(123) [7]=> string(4) "fedt" [8]=> string(3) "ert" [9]=> string(4) "erto" }
object(mysqli_stmt)#4 (10) { ["affected_rows"]=> int(-1) ["insert_id"]=> int(0) ["num_rows"]=> int(0) ["param_count"]=> int(10) ["field_count"]=> int(0) ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["sqlstate"]=> string(5) "00000" ["id"]=> int(1) }
What am i doing wrong!?
Thank you.
EDIT: The problem is inserting the data into the database. It simply doesn't work. When i execute no data is put in.
I think the problem lies with the $stmt->bind_param function, and inserting the data from the array.
param_count = 10 and field_count = 0!
EDIT !2!:
OK. So, it actually works! what i did wrong was specify a integer value in my user_id, i.e. when i created the user. My database uses AUTO.INCREMENT on that value, and therefore it didn't work..
Anyways, thanks for the answer. G'day!
Check if you have any errors when after each mysqli statement to isolate the error:
$stmt = $this->mysqli->prepare($query);
if ( false===$stmt ) {
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$stmtBindResult = $stmt->bind_param($binding,$variables[0],$variables[1],$variables[2],$variables[3],$variables[4],$variables[5],$variables[6],$variables[7],$variables[8],$variables[9]);
if ( false===$stmtBindResult ) {
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmtExecuteResult = $stmt->execute();
if ( false===$stmtExecuteResult ) {
die('execute() failed: ' . htmlspecialchars($stmt->error));
}
else you can use basic PDO. I would use PDO insert with following basic function:
$Query = "INSERT INTO user VALUES (?,?,?,?,?,?,?,?,?,?)";
$Params = array($variables[0],$variables[1],$variables[2],$variables[3],$variables[4],$variables[5],$variables[6],$variables[7],$variables[8],$variables[9]);
$InsertResult = PDOInsert($Query, $Params);
function PDOInsert($Query, $Parameters)
{
try
{
$PDOConnection = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
$PDOConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$Statement = $PDOConnection->prepare($Query);
foreach ($Parameters as $Key => $Val)
$Statement->bindValue($Key+1, $Val);
$Statement->execute();
$PDOConnection = null;
return true;
}
catch(PDOException $e)
{
die('ERROR: ' . $e->getMessage());
return false;
}
}

mysqli Object returned instead of result

I am running
$this->db->query("SELECT `id` FROM $table WHERE $table.id ='$product_id'");
that should return 92 but its returning the below why?
object(CI_DB_mysqli_result)#150 (8) { ["conn_id"]=> object(mysqli)#16
(18) { ["affected_rows"]=> int(1) ["client_info"]=> string(6) "5.5.30"
["client_version"]=> int(50530) ["connect_errno"]=> int(0)
["connect_error"]=> NULL ["errno"]=> int(0) ["error"]=> string(0) ""
["field_count"]=> int(1) ["host_info"]=> string(25) "Localhost via
UNIX socket" ["info"]=> NULL ["insert_id"]=> int(0) ["server_info"]=>
string(10) "5.5.31-cll" ["server_version"]=> int(50531) ["stat"]=>
string(150) "Uptime: 106781 Threads: 14 Questions: 30097132 Slow
queries: 13 Opens: 1937675 Flush tables: 1 Open tables: 400 Queries
per second avg: 281.858" ["sqlstate"]=> string(5) "00000"
["protocol_version"]=> int(10) ["thread_id"]=> int(373292)
["warning_count"]=> int(0) } ["result_id"]=> object(mysqli_result)#161
(5) { ["current_field"]=> int(0) ["field_count"]=> int(1)
["lengths"]=> NULL ["num_rows"]=> int(1) ["type"]=> int(0) }
["result_array"]=> array(0) { } ["result_object"]=> array(0) { }
["custom_result_object"]=> array(0) { } ["current_row"]=> int(0)
["num_rows"]=> NULL ["row_data"]=> NULL}
It is returning mysqli_ object.So Try to get the result like
$query = $this->db->query("SELECT `id` FROM $table WHERE $table.id ='$product_id'");
$result = $query->result();
foreach($result as $row)
{
echo "Id is ".$row['id']."<br>";
}
And it is appreciable that you are using mysqli_* functions instead of deprecated mysql_* functions
It's returning a mysqli_result object, exactly as the manual says it does.
To get the actual id you need to call fetch_assoc() (or similar) on the object.
if ($result = $this->db->query("SELECT id FROM $table WHERE $table.id ='$product_id'")) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("Fetched ID: %s\n", $row["id"]);
}
/* free result set */
$result->free();
}
Basically the statement:
$this->db->query("SELECT 'id' FROM $table WHERE $table.id ='$product_id'");
returns an object that can be used to extract the result set or table and assigned to a variable... so you need to create a variable and assign the result set to it as:
$mysqli = new mysqli("localhost","rinonymous","03318987165oo","rinonymous");
if ($mysqli->connect_errno) {
print_r($mysqli->connect_error);
exit();
}
$site_title = "Rinonymous";
$page_title = "";
$page_body = "";
#Page Setup
$query_page_info = "select * from pages where id = 1";
foreach ($mysqli->query($query_page_info) as $row) {
print_r($mysqli->query($query_page_info));
#query method returns an associate array
print_r($row);
$page_title = $row['title'];
$page_body = $row['body'];
}

Categories