Im new to PDO, heard that this is the better method to do web applications, and im developing small billing application.
Having one dobut, can i do coding like below?
<?php
require_once '../../classes/PDO_connection.php';
$type = 'initial_stock';
$item_code = $_POST["item_code"];
$category = $_POST["category"];
$variety = $_POST["variety"];
$quantity = $_POST["quantity"];
$price = $_POST["price"];
$f_price = number_format($price, '2', '.', '');
$total = $quantity * $price;
$full_name = $item_code.':'.$category.':'.$variety.':'.$f_price;
$in_stock = $quantity;
$prev_stock = '';
//inserting data from initial stock page
$stmt = $pdo->prepare("INSERT INTO silk (type, item_code, category, variety, quantity, price, full_name, total, in_stock, sale_date, entered_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, now(), now())");
$stmt->bindParam(1, $type);
$stmt->bindParam(2, $item_code);
$stmt->bindParam(3, $category);
$stmt->bindParam(4, $variety);
$stmt->bindParam(5, $quantity);
$stmt->bindParam(6, $price);
$stmt->bindParam(7, $full_name);
$stmt->bindParam(8, $total);
$stmt->bindParam(9, $in_stock);
$stmt->execute();
//getting all initial stock for dispaling
$stmt = $pdo->prepare("SELECT * FROM silk WHERE type='initial_stock'");
$stmt->execute();
$rows = $stmt->fetchAll();
foreach($rows as $stock){
echo "<tr class='active'>
<td>".$stock['item_code']."</td>
<td>".$stock['category']."</td>
<td>".$stock['variety']."</td>
<td>".$stock['price']."</td>
<td>".$stock['quantity']."</td>
<td><a id='initial_stock_silk_delete' id_to_delete=".$stock['id'].">Delete</a></td>
</tr>";
}
In mysql, i call the function that has query and return the value, but i thought PDO no need that? am i correct? expecting proffesionals advice.... thanks.
It's entirely up to you. If you want to use a function you already accustomed with - nobody forbids you from creating one.
The only thing you MUST take into account - such a function should accept at least TWO arguments - a query with placeholders and an array with data to bind
Related
Everything is Working Fine No Error. But I don't Know Why data is not posted on my database.
I'm new TO flutter so I need these Code Using tutorials. Get Method is Working Fine but Post method not working.
IN localhost code was working Now I hosted this project database on the server
This is my database File. Create.php
<?php
include "db.php";
$name = isset($_POST['name']) ? $_POST['name'] : '';
$desciption = isset($_POST['desciption']) ? $_POST['desciption'] : '';
$addr = isset($_POST['addr']) ? $_POST['addr'] : '';
$image_url = isset($_POST['image_url']) ? $_POST['image_url'] : '';
$price = isset($_POST['price']) ? $_POST['price'] : '';
$stmt = $db->prepare("INSERT INTO house (name, desciption,addr,image_url,price) VALUES (?, ?,?,?, ?)");
$result = $stmt->execute([$name, $desciption,$addr,$image_url,$price]);
echo json_encode($result);
When I'm Clicking on Submit Button on error get is this
API response
I need your support. I am posting the question again because it's not been solved past 8 days
Thanks in Advance
$stmt = $db->prepare("INSERT INTO house (name, desciption,addr,image_url,price) VALUES (?, ?,?,?, ?)");
$result = $stmt->execute([$name, $desciption,$addr,$image_url,$price]);
in this section should also bind the parameters because you are using prepared statements.
$stmt = $db->prepare("INSERT INTO house (name, desciption,addr,image_url,price) VALUES (?, ?,?,?, ?)");
$stmt->bind_param("sssss", $name, $desciption, $addr, $image_url, $price);
// s means string so if the price is not string you can change it to integer (i) or double (d)
$result = $stmt->execute();
If this does not work please change bind_param part to:
$stmt->bindParam(1, $name, PDO::PARAM_STR);
$stmt->bindParam(2, $desciption, PDO::PARAM_STR);
$stmt->bindParam(3, $addr, PDO::PARAM_STR);
$stmt->bindParam(4, $image_url, PDO::PARAM_STR);
$stmt->bindParam(5, $name, PDO::PARAM_STR);
And you have typo in desciption, it should be "description"
I am new into a database, I am developing an inventory management, I have four tables, two for purchase and purchase_detail. And two other for sale and sale_detail.
This image is my purchase_detail table
and this is the code for inserting new purchase and it works fine.
$sql_insert_sale = "INSERT INTO
purchase(recipt_no,date,total,vat,totalwithvat) VALUES ( ?, ?, ? ,?,
?)";
$query = $dbh->prepare($sql_insert_sale);
$query->bindParam(1, $recipt_no, PDO::PARAM_STR);
$query->bindParam(2, $date, PDO::PARAM_STR);
$query->bindParam(3, $price_all, PDO::PARAM_STR);
$query->bindParam(4, $vat_all, PDO::PARAM_STR);
$query->bindParam(5, $total_all, PDO::PARAM_STR);
$query->execute();
$lastInsertId = $dbh->lastInsertId();
if ($lastInsertId) {
$sql_insert_purchase = "INSERT INTO
purchase_detail(purchase_id, product_id,vat,price,quantity,amount) "
. "VALUES ( :purchase_id
,:product_id,:vat,:price,:quantity,:amount)";
for($i=0;$i<count($partnumber);$i++) {
$data=array(
':purchase_id'=> $lastInsertId,
':product_id'=> $id[$i],
':vat'=> $vat[$i],
':price'=> $amount[$i],
':quantity'=> $quantity[$i],
':amount'=> $total[$i]
);
$statement = $dbh->prepare($sql_insert_purchase);
if($statement->execute($data)){
echo "Successfull";
}else{
print_r($dbh->errorInfo());
}
and this is my sale_detail table
I have a problem with sale table, when updating the quantity in the purchase_detail table. As you can see we have same product with different quantity, when I make a new sale it always updates the only quantity of the row with the product_id that comes first. Below is the code for making new sale
$sql_insert_sale = "INSERT INTO
sale(recipt_no,cus_name,date,total)VALUES ( ?,?, ?, ? )";
$query = $dbh->prepare($sql_insert_sale);
$query->bindParam(1, $recipt_no, PDO::PARAM_STR);
$query->bindParam(2, $cus_name, PDO::PARAM_STR);
$query->bindParam(3, $date, PDO::PARAM_STR);
$query->bindParam(4, $total_all, PDO::PARAM_STR);
$query->execute();
$lastInsertId = $dbh->lastInsertId();
if ($lastInsertId) {
$sql_insert_sale = "INSERT INTO
sale_detail(sale_id, product_id,vat,price_vat,quantity,amount) "
. "VALUES ( :sale_id,:product_id,:vat,:price_vat,:quantity,:amount)";
for($i=0;$i<count($partnumber);$i++) {
$data=array(
':sale_id'=> $lastInsertId,
':product_id'=> $id[$i],
':vat'=> $vat[$i],
':price_vat'=> $price[$i],
':quantity'=> $quantity[$i],
':amount'=> $total[$i]
);
$statement = $dbh->prepare($sql_insert_sale);
if($statement->execute($data)){
$sql_update_purchase="UPDATE purchase_detail
INNER JOIN product "
.
"on(purchase_detail.product_id=product.product_id) "
. "SET
purchase_detail.quantity=purchase_detail.quantity-$quantity[$i]"
. " WHERE
purchase_detail.product_id=$id[$i] and product.product_id=$id[$i]";
$statement_update=$dbh->prepare($sql_update_purchase);
if($statement_update->execute())
Please, tell what's wrong with my code, I really appreciate your help. I am nearly close to my deadline for finishing it.
I'm trying to insert some value into my database, but I got no result, but the code got no error, and the result label said it is succeed. My database connection working. How to check the issue here, I confused.
My Code Here
// insert new data to menu table
$sql_query = "INSERT INTO tbl_jadwal (Nama_Lokasi, Category_ID, Longitude, Latitude, Phone, Email, Menu_image, Description)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
$upload_image = 'upload/images/' . $menu_image;
$stmt = $connect->stmt_init();
if ($stmt->prepare($sql_query))
{
// Bind your variables to replace the ?s
$stmt->bind_param('sssssss',
$nama_lokasi,
$category_ID,
$longitude,
$latitude,
$phone,
$email,
$upload_image,
$description
);
// Execute query
$stmt->execute();
// store result
$result = $stmt->store_result();
$stmt->close();
}
This should do, you were missing one s in the param string
$stmt->bind_param('ssssssss',
$nama_lokasi,
$category_ID,
$longitude,
$latitude,
$phone,
$email,
$upload_image,
$description
And you have way too much code. Only a very little part of it is relevant
Can some onw please explain what is wrong with this ... this worked completely fine with procedural php
function foo(){
$incomingtime = date('Y-m-d H:i:s', time());
$stmt = $db->stmt_init();
$id = "Abc123" ;
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$stmt->execute();
printf("Affected rows (UPDATE): %d\n", $db->affected_rows); // Always return 1
$stmt->close();
}
But nothing goes in the database.
Datatype in mysql db for indate is datetime
There's several issues with this code.
$stmt_4 is used before it's defined.
$u_id and $c_id are both defined then not used.
Trying to execute $stmt without supplying parameters.
$db is not defined.
$id is not defined.
If you are trying to convert working code to a function make sure that either the function gets these passed in as an argument, they are marked as global or the function creates/ retrieves them.
Check changing:
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('ssii', $incomingtime, $id, $u_id, $c_id);
$u_id = 1;
$c_id = 1;
$stmt->execute();
to:
$u_id = 1;
$c_id = 1;
$query = "INSERT INTO table (indate, myid, uniqueid, commonid)
VALUES (CURRENT_TIMESTAMP, ?, ?, ?)"
$stmt = $db->prepare($query);
$stmt->execute(array($id, $u_id, $c_id));
NOTE: I deleted the parameter ssii because it's not considered in the query. It only expects 4 parameters.
I was wondering if someone could help me.
Im trying to integrate some code into my application, the code that i need to integrate is written with PDO statements and i have no idea how it goes.
I was wondering if someone could help me convert it.
The code is as follows
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
$stmt = $PDO->prepare($sql);
$stmt->execute($args);
if (empty($mid)) {
$mid = $PDO->lastInsertId();
}
$insertSql = "insert into message2_recips values ";
$holders = array();
$params = array();
foreach ($rows as $row) {
$holders[] = "(?, ?, ?, ?)";
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
$insertSql .= implode(',', $holders);
$stmt = $PDO->prepare($insertSql);
$stmt->execute($params);
You shoudl use PDO unles for some technical reason you cant. If you dont know it, learn it. Maybe this will get you started:
/*
This the actual SQL query the "?" will be replaced with the values, and escaped accordingly
- ie. you dont need to use the equiv of mysql_real_escape_string - its going to do it
autmatically
*/
$sql = "insert into message2 (mid, seq, created_on_ip, created_by, body) values (?, ?, ?, ?, ?)";
// these are the values that will replace the ?
$args = array($mid, $seq, '1.2.2.1', $currentUser, $body);
// create a prepared statement object
$stmt = $PDO->prepare($sql);
// execute the statement with $args passed in to be used in place of the ?
// so the final query looks something like:
// insert into message2 (mid, seq, created_on_ip, created_by, body) values ($mid, $seq, 1.2.2.1, $currentUser, $body)
$stmt->execute($args);
if (empty($mid)) {
// $mid id is the value of the primary key for the last insert
$mid = $PDO->lastInsertId();
}
// create the first part of another query
$insertSql = "insert into message2_recips values ";
// an array for placeholders - ie. ? in the unprepared sql string
$holders = array();
// array for the params we will pass in as values to be substituted for the ?
$params = array();
// im not sure what the $rows are, but it looks like what we will do is loop
// over a recordset of related rows and do additional inserts based upon them
foreach ($rows as $row) {
// add a place holder string for this row
$holders[] = "(?, ?, ?, ?)";
// assign params
$params[] = $mid;
$params[] = $seq;
$params[] = $row['uid'];
$params[] = $row['uid'] == $currentUser ? 'A' : 'N';
}
// modify the query string to have additional place holders
// so if we have 3 rows the query will look like this:
// insert into message2_recips values (?, ?, ?, ?),(?, ?, ?, ?),(?, ?, ?, ?)
$insertSql .= implode(',', $holders);
// create a prepared statment
$stmt = $PDO->prepare($insertSql);
// execute the statement with the params
$stmt->execute($params);
PDO really is better. It has the same functionality as MySQLi but with a consistent interface across DB drivers (ie. as long as your SQL is compliant with a different database you can theoretically use the exact same php code with mysql, sqlite, postresql, etc.) AND much better parameter binding for prepared statements. Since you shouldnt be using the mysql extension any way, and MySQLi is more cumbersome to work with than PDO its really a no-brainer unless you specifically have to support an older version of PHP.