php - mssql_fetch_array - php

I am trying to update an MSSQL database through PHP, as shown in in the following code. The problem is that the first 5 lines of code are successfully being executed but the program is not entering in the while loop. I am sure that the array $items contains records.
function updateOrder($items, $cardNo){
if($items){
$orderid = generateGuid();
$username = $_SESSION['username'];
$query = "INSERT INTO Orders (OrderId, OrderDate, OrderStatus, OrderCardNo, OrderDiscount, OrderVatRate, CustomerUsername) ";
$query .= " VALUES ('".mssql_guid_string($orderid)."',".date('Y-m-d').", 'PE', '$cardNo', 0, 0.18, '$username')";
$result = mssql_query($query) or die("Unable to place order"/*mssql_get_last_message()*/);
while($row = mssql_fetch_array( $items )){
$tmpId = generateGuid();
$tmpPrice = getUserPrice($username, $row["ProductId"]);
$query = "INSERT INTO Orders_Details (OrderDetailsId, ProductPrice, Qty, OrderId, ProductId)";
$query .= "VALUES ('".mssql_guid_string($tmpId)."', $tmpPrice, '".$row["Qty"]."', '".mssql_guid_string($orderid)."', 0, 0.18, '".$row["ProductId"]."')";
echo($query);
$result = mssql_query($query) or die("Unable to place order"/*mssql_get_last_message()*/);
}
}
}

mssql_fetch_array takes a parameter that is the return of a mssql_query : http://php.net/manual/en/function.mssql-fetch-array.php. What is $items?

Something worng with $items in while($row = mssql_fetch_array( $items )) either it's having no value or you are sending wrong in $items
If items having any value like items id then run a select query for selecting items having id in $items and use return of mssql_query in mssql_fetch_array

could it be that the date should be escaped?
Code:
$query = "INSERT INTO Orders (OrderId, OrderDate, OrderStatus, OrderCardNo, OrderDiscount, OrderVatRate, CustomerUsername) ";
$query .= " VALUES ('".mssql_guid_string($orderid)."',".date('Y-m-d').", 'PE', '$cardNo', 0, 0.18, '$username')";
$query may look like:
INSERT INTO Orders (OrderId, OrderDate, OrderStatus, OrderCardNo, OrderDiscount,
OrderVatRate, CustomerUsername)
VALUES ('100',2012-1-20,'PE','10', 0, 0.18, 'username')

I solved the problem by separating the 2 UPDATE actions into two different methods and call the method that populates $items twice.

The last query before while($row = mssql_fetch_array( $items )) is an INSERT, so mssql_fetch_array() will never fetch anything!

Related

query result array in loop for another query

I Queried Database Table 'users' for 'user_id'. and get an array of ids.
$sel = "SELECT user_id FROM users WHERE status='Approved'";
$result = #mysqli_query ($dbcon, $sel);
Then i inserted values into another table income for all those user ids.
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$ins = "INSERT INTO income (user_id, income_amount) VALUES ('$row', '100')";
$giv = #mysqli_query ($dbcon, $ins);
}
Notice: Array to string conversion in E:\xampp\htdocs\project\t.php on line 109
Can anyone help me resolve this issue.
$sel = "SELECT user_id FROM users WHERE status='Approved'";
$result = #mysqli_query ($dbcon, $sel);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$ins = "INSERT INTO income (user_id, income_amount) VALUES ('" . $row['user_id'] . "', '100')";
$giv = #mysqli_query ($dbcon, $ins);
}
First , Check if $results is in array ..you can put some error handling checked is_array($result).
If it is fine then pass it to mysqli_fetch_array().
Do't add suppress # error ,while developing.
i would like to suggest you a single query for that so after that you need not to use while loop to insert your data in income table:
Just try it :
INSERT INTO income (user_id,income_amount) SELECT user_id,'100' AS income_amount FROM users WHERE status = 'Approved';
You can use it like that way :
$sel = "INSERT INTO income (user_id,income_amount) SELECT user_id,'100' AS income_amount FROM users WHERE status = 'Approved'";
$result = #mysqli_query ($dbcon, $sel);

How to insert multiple values in a single query

Please somebody help me. In below code the query will execute 3 times , means query execution will depend on number of elements in array.
Please guide me how to run this query with inserting all data at once
$products = array("shirt" , "paint" , "socks");
$price = array("200" , "600" , "50");
$quantity = array("3" , "2" , "2");
$num = 0; while($num <= count($products))
{
$mysqli->query("insert into new_order set
product = '".$products[$num]."' ,
price = '".$price[$num]."' ,
quantity = '".$quantity[$num]."'
");
$num++;
}
It won't throw any error untill you'll be getting same number of values within an array
$counts = count($products);
$query = "insert into new_order (product,price,quantity) values ";
foreach($products as $key => $value){
$query .= "('$value','$price[$key]','$quantity[$key]')";
$query .= (++$key == $counts) ? '' : ',';
}
$mysqli->query($query);
Query looks like:
//insert into new_order (product,price,quantity) values('shirt','200','3'),('paint','600','2'),('socks','50','2')
Iterate over each item in $products to build $sql string:
$sql = "insert into new_order(product, price, quantity) values ";
for($i=0;$i<count($products);$i++){
$sql .= "({$products[$i]}, {$price[$i]}, {$quantity[$i]}),";
}
$sql = substr($sql,0,-1); //cut off the trailing comma
$mysqli->query($sql);
// insert into new_order(product, price, quantity) values (shirt, 200, 3),(paint, 600, 2),(socks, 50, 2)

PHP stops at, and shows, a single line of code

Recently I copied a PHP script to use it for another database. After I correctly edited all the words and links, I got an weird error.
SELECT naam, aantal, prijs
FROM boeken, bestelling
WHERE boeken.Boekcode = bestelling.Boekcode
AND bestelling.Boekcode IN ('101','102')
AND bestelnummer = 3;
It's not a regular error that say something like
Error on line 42
Basically what the code does, is that when you order books and filled in a form (Name, last name, email etc) it puts that in a database. And afterwards puts it in a "thankyou.html" page.
Here's part of the code that causes this
mysqli_query($con, $query) or die($query . "<br>");
$bestelnummer = MYSQLI_INSERT_ID($con);
$object = array_filter($object);
$objectnaam = join("','",array_keys($object));
$object = http_build_query($object);
$object = str_replace('=', ',', $object);
$object = str_replace('&', "),($bestelnummer,", $object);
$query = "INSERT INTO bestelling (bestelnummer, Boekcode, aantal) VALUES ($bestelnummer,$object)";
$result = mysqli_query($con, $query) or die($query."<br>");
$aantal = "SELECT naam, aantal, prijs FROM boeken, bestelling WHERE boeken.Boekcode = bestelling.Boekcode AND bestelling.Boekcode IN ('".$objectnaam."') AND bestelnummer = $bestelnummer";
$result = mysqli_query($con, $aantal) or die($aantal . "<br>");
$res = mysqli_fetch_all($result);
$prijs = 0;
The $object is an array of the books you choose.
I've Google'd for this problem, and yes, I have Apache and everything enabled.
Sorry if I'm unclear, it's been a while, I can answer any questions you might have.
Well you echo out the query if it fails.
$aantal = "SELECT naam, aantal, prijs FROM boeken, bestelling WHERE boeken.Boekcode = bestelling.Boekcode AND bestelling.Boekcode IN ('".$objectnaam."') AND bestelnummer = $bestelnummer";
$result = mysqli_query($con, $aantal) or die($aantal . "<br>");
You might want to check the error message that is returned from the database using mysqli_error().
$result = mysqli_query($con, $aantal) or die(mysqli_error() . "<br>");
first need to refine
$query = "INSERT INTO bestelling (bestelnummer, Boekcode, aantal) VALUES ($bestelnummer,$object)";
you are selecting values insertion for 3 columns and passing only two values
For second query try to use backticks for tablename and column

implode or explode mysql_fetch_array in php

Hi guys.
I'm currently try to make an mysql query than take the results and use them in an another query. So I thought I'm calling my database and use mysql_fetch_array and than implode it do insert , so I can use it in an another query. I read here many questions about this and based on the questions i wrote my own piece of code but I'm getting this error:
Warning: array_values() expects parameter 1 to be array, string given in /var/www/html/lager_management/warenkorb.php on line 107
Warning: implode(): Invalid arguments passed in /var/www/html/lager_management/warenkorb.php on line 108
Here is the piece of code what is going wrong I can't explain myself and I know mysql is old and I should use myqli
$sql3 = "SELECT `Index` FROM lm_Warenkorb;";
$result3 = mysql_query($sql3);
while($resultarray3 = mysql_fetch_array($result3))
{
$anfrage = array();
$anfrage = $resultarray3['Index'];
$anfrage = implode(", ", $anfrage);
$sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".$anfrage.");";
}
The table lm_Warenkorb looks like this:
Index:
10
2
6
I think you could do it using one query with nested SELECT:
$sql3 = "
SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort`
FROM `lm_Artikel`
WHERE `Index` IN (
SELECT `Index` FROM lm_Warenkorb
)";
$result3 = mysql_query($sql3);
while($resultarray3 = mysql_fetch_array($result3)) {
// handle the results
}
you use mysql_fetch_array($result) in a while loop, which is perfectly right.
But this obviously will only return one row of your table from database and not the whole column.
therefore $resultarray3['Index']; returns the value of Index column of your first table row, which is not an array.
Try this
$anfrage = array();
while($resultarray3 = mysql_fetch_array($result3))
{
$anfrage[] = $resultarray3['Index'];
}
if(count($anfrage) > 0) {
$anfrage = implode(",", $anfrage);
$sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".$anfrage.");";
}
$sql3 = "SELECT `Index` FROM lm_Warenkorb;";
$result3 = mysql_query($sql3);
$data = array(0);
while($resultarray3 = mysql_fetch_assoc($result3))
{
$data[] = $resultarray3['Index'];
}
$sql2 = "SELECT `Index`, `Artikelbezeichnung`, `Status`, `Bestand`, `Lieferant`, `Datum-Einlagerung`, `Lagerort` FROM `lm_Artikel` WHERE `Index` IN (".implode(',', $data).");";
echo $sql2;

select from mysql db with 300 tables using a default prefix

I have a program that selects from about 200 tables with prefix. eg PBN_products, PBN_address, PBN_others.
Instead of appending the prefix on each table for the select statement, is there a way of defining the prefix as default value and do the selection?
$prefix=GET['prefix'];
mysql_connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD);
mysql_select_db(DB_DATABASE);
$sql = 'SELECT price, description, title, cost'.
'FROM products, address, others';
How can I define the prefix not to include in all tables? I have 200 tables.
I would look into a class to do some simple query abstraction or some kind of ORM lib that does this. A sample would be like this.
class Query {
function from($tbl){
return new Table($tbl);
}
}
class Table {
var $prefix = 'PBN_';
var $tblname = '';
function Table($name){
$this->tblname = $this->prefix.$name;
}
function select($cols, $where = false, $order = false, $limit = false){
$query = "SELECT {$cols} FROM {$this->tblname}";
if($where) $query .= " WHERE ".$where; //add where
if($order) $query .= " ORDER BY ".$order; //add order
if($limit) $query .= " LIMIT ".$limit; //add limit
return $query;
}
}
$q = new Query;
$results = mysql_query($q->from('products')->select('*'));
This is obviously nowhere near complete or secure. Just a sample of how an abstraction class could speed up your sql and do you your prefixes for you.
You could define an array with the table names, and loop through that array. When you append the array item to the string, put "PBN_" hardcoded in front of that name.
$arr = array("products","address","others");
$sql = "SELECT price, description, title, cost FROM ";
foreach ($arr as $tablename) {
$sql = $sql . "PBN_" . $tablename . ", ";
}
$sql = substr($sql, 0, -2); // Remove last comma
You can then add all the tablenames to the array, and the prefix will automatically be added.
How about something like this?
$prefix = GET['prefix'];
// add prefix to table names
foreach (array("products", "address", "others") as &$table)
{
$table = $prefix.$table;
}
mysql_connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD);
mysql_select_db(DB_DATABASE);
$sql = 'SELECT price, description, title, cost'.
'FROM '.$table[0].', '.$table[1].', '.$table[2];
You could do something like this?
$prefix = '';
if(isset($_GET['prefix'])){
$prefix = mysql_real_escape_string(stripslashes($_GET['prefix']));
}
$sql = "SELECT price, description, title, cost
FROM {$prefix}products, {$prefix}address, {$prefix}others";
EDIT: I agree on the comments that this is bad practice... An alternative would be to store the prefixes in another table and pass an ID of that table in the GET. This would make you less vulnarable to SQL injections.
$prefix = "";
if(isset($_GET['prefixid'])){
$prefixid = mysql_real_escape_string(stripslashes($_GET['prefixid']));
$query = "SELECT prefix FROM prefixes WHERE prefixid = $prefixid";
$result = mysql_query($query);
$prefix = mysql_result($result, 0, 0);
}
$sql = "SELECT price, description, title, cost
FROM {$prefix}products, {$prefix}address, {$prefix}others";

Categories