Query does not do what I want it to do - php

$mpn = $P[0];
$qty = $P[14];
$mysql_connection = mysql_connect('localhost', 'my_db', 'my_pass');
if (!$mysql_connection) {
die('Could not connect to db: ' . mysql_error());
}
mysql_select_db('my_db', $mysql_connection);
$id = mysql_query("SELECT productid FROM my_table_2 WHERE value = '$mpn'");
if (!$id) {
return("XXX-99999");
}
mysql_select_db('my_db', $mysql_connection);
$sku = mysql_query("SELECT productcode FROM my_table WHERE productid = $id");
if (!$sku) {
return("XXX-99999");
}
mysql_select_db('my_db', $mysql_connection);
$qty2 = mysql_query("SELECT avail FROM my_table WHERE productcode = '$sku'");
if (!$qty2) {
return("XXX-99999");
}
if ($qty2 <1 && $qty >0 && $qty2 != $qty) {
return($sku);
}
else {
return("XXX-99999");
}
I'm trying to match Manufacturers part numbers from Product feed and database to accomplish putting out of stock products from main source to secondary source. It does not work. What I am doing wrong?
This has been edited to try and explain the situation more clearly. First this is going into an app and is a snippit to be used by that app. Hence mysql instead of mysqli. The variable $mpn in the first query comes from $mpn = ($P[0]); at the top. It is in a feed and not in the database as a column. $sku in the second query comes from the result of the first query and is not in the database as a column. The app loops this code for each line of the feed.
The above fails to achieve the desired effect of providing the last argument even though I know it for sure should (I set it up). Given the new explaination can somebody help?
$mpn = ($P[0]);
$qty = ($P[14]);
$mysql_connection = mysql_connect('localhost', 'user', 'pass' );
if (!$mysql_connection) {
die('Could not connect to db: ' . mysql_error());
}
mysql_select_db('db', $mysql_connection);
$tmp1 = mysql_query("SELECT productcode FROM table1 WHERE mpn != '' && mpn = '$mpn'")or die(mysql_error());
$row1 = mysql_fetch_array($tmp1, MYSQL_BOTH);
$sku = $row1[0];
$tmp2 = mysql_query("SELECT avail FROM table1 WHERE productcode = '$sku'")or die(mysql_error());
$row2 = mysql_fetch_array($tmp2, MYSQL_NUM);
$qty2 = $row2[0];
if ($qty2 <=0 && $qty >0) {
return($sku);
}
else {
return("XXX-99999");
}

You have to fetch the data after mysql_query(look into mysqli instead) using mysql_fetch_array. After fetching assign $row1 = mysql_fetch_array($id); and then you can call the row and column name $row1['productid'];. You also do not need to open assign the database before every call. You can only do it once before running the queries and then run mysql_close($mysql_connection)
$mpn = $P[0];
$qty = $P[14];
$mysql_connection = mysql_connect('localhost', 'my_db', 'my_pass');
if (!$mysql_connection) {
die('Could not connect to db: ' . mysql_error());
}
mysql_select_db('my_db', $mysql_connection);
$id = mysql_query("SELECT productid FROM my_table_2 WHERE value = '$mpn'");
$row1 = mysql_fetch_array($id);
if (!$id) { return("XXX-99999");
}
$sku = mysql_query("SELECT productcode FROM my_table WHERE productid = $row1['productid']");
$row2 = mysql_fetch_array($sku);
if (!$sku) { return("XXX-99999");
}
$qty2 = mysql_query("SELECT avail FROM my_table WHERE productcode = '$row2['productcode']'");
$row3 = mysql_fetch_array($qty2);
if (!$qty2) { return("XXX-99999");
}
if ($row3['avail'] <1 && $qty >0 && $row3['avail'] != $qty) { return($row['productcode']);
}
else {return("XXX-99999");
}
mysql_close($mysql_connection);
This should give you more or less an idea. Use as reference: http://www.php.net/manual/en/function.mysql-connect.php

Here:
$sku = mysql_query("SELECT productcode FROM my_table WHERE productid = $id");
I think it should look like:
$sku = mysql_query("SELECT productcode FROM my_table WHERE productid = '$id' ");

Related

Comparison for in SQL row selection not working?

This is the code that is not working:
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
//THIS SHOULD NOT BE RUNNING
}
I've verified over and over in phpMyAdmin and the text_id in the table and $last_id are both the integer value '1'. That being said, the condition equates to true every time the code runs.
Am I messing this code up, or is my thinking improper?
Here is entire script:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$last_id_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$last_id_query = "SELECT alias FROM $last_id_table WHERE alias = '$alias'";
$last_id_result = mysqli_query($connection,$last_id_query);
$last_id_rows = mysqli_fetch_array($last_id_result);
if ($last_id_rows['alias'] === $alias)
{
$last_id = $last_id_rows['last_id'];
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
$last_row_id = $row['text_id'];
}
}
//UPDATE LAST SYNC ID
$update_query = "UPDATE $last_id_table SET last_id = '$last_row_id' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "INSERT INTO $last_id_table (alias, last_id) VALUES('$alias','-1')";
mysqli_query($connection,$update_query);
}
?>
You should change ;
WHERE text_id > '$last_id'
to
WHERE text_id > $last_id
text_id column is integer and can't be compared like string.

perform two computation in two column and the answer will be save in another column

How can I perform a autocompute in my database ex. the value of Stock and Quantity(Quantity-Stock) the answer will be save in CarryO column
create.php
<?php
require_once 'dbconfig.php';
$con = mysql_connect("localhost","root","");
if($con)
{
mysql_select_db("testproduct",$con);
}
if($_POST)
{
$sql = mysql_query("SELECT * FROM tblproduct WHERE id = '".$_POST['pid']."'");
$prod = mysql_fetch_array($sql);
$pname = $prod['name'];
$actualprice = $prod['actualprice'];
$sellprice = $prod['sellprice'];
$stock = $prod['Stock'];
$gname = $_POST['gname'];
$saledate = $_POST['saledate'];
$quantity = $_POST['quantity'];
$profit = $_POST['profit'];
$carryO = $_POST['carryO'];
$sells = $_POST['sells'];
$expense = $_POST['expense'];
try{
$stmt = $db_con->prepare("INSERT INTO tblsales(pname,gname,saledate,quantity,actualprice,sellprice,carryO,sells,expense,profit,stock)
VALUES(:upname,:ugname,:usaledate,:uquantity,:uactualprice,:usellprice,:ucarryO,:usells,:uexpense,:uprofit,:ustock)");
$stmt->bindParam(":upname", $pname);
$stmt->bindParam(":ugname", $gname);
$stmt->bindParam(":usaledate", $saledate);
$stmt->bindParam(":uquantity", $quantity);
$stmt->bindParam(":uactualprice", $actualprice);
$stmt->bindParam(":usellprice", $sellprice);
$stmt->bindParam(":ucarryO", $carryO);
$stmt->bindParam(":usells", $sells);
$stmt->bindParam(":uexpense", $expense);
$stmt->bindParam(":uprofit", $profit);
$stmt->bindParam(":ustock", $stock);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
thanks for your help just new in php and please let me know if I can use your code or its only a example
Change this part:
$prod = mysql_query("SELECT * FROM tblproduct WHERE id = ".$_POST['pid']);
echo $prod;
$pname = [$prod['name']];
Into:
$sql = mysql_query("SELECT * FROM tblproduct WHERE id = '".$_POST['pid']."'");
$prod = mysql_fetch_array($sql);
$pname = $prod['name'];
You may want to try this.
$prod = mysql_query("SELECT * FROM tblproduct WHERE id = ".$_POST['pid'],$db_con); //$db_con must be your database connection
if(!$prod) { die("Database query failed: " . mysql_error()); } //always check if your query is properly done.
$pname = "";
while ($row = mysql_fetch_array($prod)) {
$pname = $row["name"]; }
also if you are fetching only one column which is the name then be specific to your query for fastest result. e.g. "SELECT name FROM tblproduct WHERE id = ".$_POST['pid']

MYSQL Results; no records found statement [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Display Data From MYSQL; SQL statement error
I have the code below displaying data from a MYSQL database (currently looking into sql injection issue) I need to insert an error message when no results are found...not sure where to position this! I have tried the code if( mysql_num_rows($result) == 0) {
echo "No row found!" but keep on gettin syntax errors, does anyone know the correct position in the code for this?
--
require 'defaults.php';
require 'database.php';
/* get properties from database */
$property = $_GET['bedrooms'] ;
$sleeps_min = $_GET['sleeps_min'] ;
$availability = $_GET['availability'] ;
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
$result = do_query("SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'", $db_connection);
while ($row = mysql_fetch_assoc($result))
{
$r[] = $row;
}
?>
I have found few errors in your code that in line
$query = "SELECT * FROM `properties` WHERE bedrooms = '{$bedrooms}' AND sleeps_min = '{$sleeps_min}' AND availability = '{$availability}'";
$row=mysql_query($query);
You use bedrooms = '{$bedrooms}' but $bedrooms is not variable in whole cod it must be $preopery. I have made a few changes in your code given below please try it.
<?php
require 'defaults.php';
require 'database.php';
/* get properties from database */
/*if get $_GET['bedrooms'] value else ''*/
if (isset($_GET['bedrooms'])) {
$property = $_GET['bedrooms'];
} else {
$property = '';
}
/*if get $_GET['sleeps_min'] value else ''*/
if (isset($_GET['sleeps_min'])) {
$sleeps_min = $_GET['sleeps_min'];
} else {
$sleeps_min = '';
}
/*if get $_GET['availability'] value else ''*/
if (isset($_GET['availability'])) {
$availability = $_GET['availability'];
} else {
$availability = '';
}
$query = "SELECT * FROM `properties` WHERE bedrooms = '" . $property . "' AND sleeps_min = '" . $sleeps_min . "' AND availability = '" . $availability . "'";
$result = mysql_query($query) or die(mysql_error());
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
}
?>
Do var_dump($GET_) to debug whether you are getting valid strings. If any of these are blank, the query will try to match blank values instead of NULL. You should prevent this by doing:
if(!$_GET['bedrooms'] || $_GET['bedrooms'] == ''){
$property = 'NULL';
}//repeat for all three
$query = "SELECT * FROM `properties` WHERE 'bedrooms' = '$bedrooms' AND 'sleeps_min' = '$sleeps_min' AND 'availability' = '$availability'";
Instead of:
while ($row = mysql_fetch_assoc($result)) {
$r[] = $row;
}
You can simply do:
$r = mysql_fetch_array($query);
But enclose that in a conditional to see if your query found anything:
if(mysql_affected_rows() > 0){
//your code here will execute when there is at least one result
$r = mysql_fetch_array($query);
}
else{//There was either nothing or an error
if(mysql_affected_rows() == 0){
//There were 0 results
}
if(mysql_affected_rows() == -1) {
//This executes when there is an error
print mysql_error(); //not recommended except to debug
}
}

Cant get included file to connect to database

I must be missing something simple but I don't see it. The following code works great.
<?php
$res = mysql_connect("localhost", "newuser", "");
mysql_select_db("supplydb");
function filter($data)
{
$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
error_reporting(0);
require("../codebase/grid_connector.php");
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
function formatting($row)
{
$data = $row->get_value("fda_approved");
if ($data == 1)
$row->set_value("fda_approved", Yes);
else
$row->set_value("fda_approved", No);
}
$gridConn = new GridConnector($res, "MySQL");
function myUpdate($action)
{
$data6 = $action->get_id();
$cat_id = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id ='{$data6}'") or die("Error in query: $query. " . mysql_error());
$rows56 = mysql_fetch_array($cat_id, MYSQL_ASSOC);
$array = filter($rows56['category']);
$status = $action->get_value("approval_status");
$gridConn = new GridConnector($res, "MySQL");
mysql_query("UPDATE submissions SET approval_status='{$status}' WHERE submissions.submission_id='{$data6}'") or die("Error in query: $query. " . mysql_error());
$action->success;
}
$gridConn->event->attach("beforeUpdate", "myUpdate");
$gridConn->event->attach("beforeRender", "formatting");
$gridConn->render_sql("SELECT * FROM submissions JOIN products ON products.product_id = submissions.product_id and submissions.category='$array' and submissions.manufacturer_id='$array1' and submissions.approval_status='0'", "submission_id", "item_number,description,list_price,sugg_price,quantity_per_unit,fda_approved,gpo_contract_number, approval_status");
?>
This code does not
<?php
require("../site_globals/dbc_simple.php");
//$res = mysql_connect("localhost", "newuser", "");
//mysql_select_db("supplydb");
error_reporting(0);
require("../codebase/grid_connector.php");
$mask5 = filter($_GET["var1"]);
//Get Category ID
$cat = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id='$mask5'");
$rows = mysql_fetch_array($cat, MYSQL_ASSOC);
$array = filter($rows['category']);
//Get Manufactuer ID
$man = mysql_query("SELECT manufacturer_id FROM submissions WHERE submissions.submission_id='$mask5'");
$arows = mysql_fetch_array($man, MYSQL_ASSOC);
$array1 = filter($arows['manufacturer_id']);
function formatting($row)
{
$data = $row->get_value("fda_approved");
if ($data == 1)
$row->set_value("fda_approved", Yes);
else
$row->set_value("fda_approved", No);
}
$gridConn = new GridConnector($res, "MySQL");
function myUpdate($action)
{
$data6 = $action->get_id();
$cat_id = mysql_query("SELECT category FROM submissions WHERE submissions.submission_id ='{$data6}'") or die("Error in query: $query. " . mysql_error());
$rows56 = mysql_fetch_array($cat_id, MYSQL_ASSOC);
$array = filter($rows56['category']);
$status = $action->get_value("approval_status");
$gridConn = new GridConnector($res, "MySQL");
mysql_query("UPDATE submissions SET approval_status='{$status}' WHERE submissions.submission_id='{$data6}'") or die("Error in query: $query. " . mysql_error());
$action->success;
}
$gridConn->event->attach("beforeUpdate", "myUpdate");
$gridConn->event->attach("beforeRender", "formatting");
$gridConn->render_sql("SELECT * FROM submissions JOIN products ON products.product_id = submissions.product_id and submissions.category='$array' and submissions.manufacturer_id='$array1' and submissions.approval_status='0'", "submission_id", "item_number,description,list_price,sugg_price,quantity_per_unit,fda_approved,gpo_contract_number, approval_status");
?>
The only difference is the include file at the top and all the include file is is:
<?php
$res = mysql_connect("localhost", "newuser", "");
mysql_select_db("supplydb");
?>
Im fairly new to php but this seems simple and I'm not sure what is getting lost in translation. This works fine on other pages by the way so it must have something to do with the $gridConn = new GridConnector($res, "MySQL"); but I dont know enough to see what. I'm using the DHTMLX javascript library. Could it have something to do with that? Ive tried everything here. Ideas?
Im getting: XML Parsing Error: XML or text declaration not at start of entity Location
Problem is not in the database connection itself, it works correctly and generates data, but result xml corrupted, because some output was started before connector's code.
Check ../site_globals/dbc_simple.php - probably it have some whitespaces|newlines after closing "?>" tag - delete them and it will fix the problem.
Such whitespaces|newlines will not cause harm for HTML pages, but for XML data any extra char at start of document can cause a problem.

How do I pass more than one variable via URL in php?

I am trying to pass multiple variables in a URL in PHP to GET some info, but I don't think it's working.
$allowedFunctions = array(
'returnAllProducts',
'refreshCurrentProduct'
);
$IDNUM = $_GET[ 'idNum' ];
$functionName = $_GET[ 'func' ];
if( in_array( $functionName, $allowedFunctions ) && function_exists( $functionName ) )
{
$functionName();
}
Then I have the refreshCurrentProduct function:
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
$query = "SELECT `ID` FROM `PRODUCTS`";
$result = mysql_query($query) or die('Query failed:'.mysql_error());
$DB_STOCK = mysql_query("SELECT `STOCK` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_SHORT = mysql_query("SELECT `MYNAME` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_LONG = mysql_query("SELECT `DESCRIPTION` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_PRICE = mysql_query("SELECT `PRICE` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$DB_SHIP = mysql_query("SELECT `SHIPPING` FROM `PRODUCTS`") or die('Query failed:'.mysql_error());
$ID = mysql_result($result,$IDNUM,"ID");
$STOCK = mysql_result($DB_STOCK,$IDNUM,"STOCK");
$SHORT = mysql_result($DB_SHORT,$IDNUM,"MYNAME");
$LONG = mysql_result($DB_LONG,$IDNUM,"DESCRIPTION");
$PRICE = mysql_result($DB_PRICE,$IDNUM,"PRICE");
$SHIP = mysql_result($DB_SHIP,$IDNUM,"SHIPPING");
echo '
//echo $STOCK, $SHORT, etc....
';
}
The URL I am using is products.php?func=refreshCurrentProduct&idNum=4
In theory, that should display from the row with 4 in it, however, it only displays the info from the first row. If I do a $IDNUM=5 within the function, it will display the 5th row, so something is wrong with how I pass the information.
Also, how do I create (for instance) $STOCK without having to have so much code in $DB_STOCK? Seems like there has to be a better way...
Why don't you do (as others already mentioned , $IDNUM is not in the scope of the function):
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
// If $_GET['idNum'] is not a number use 0
$rowNumber = is_numeric($_GET['idNum']) ? $_GET['idNum'] : 0;
$query = "SELECT ID, STOCK, MYNAME, DESCRIPTION, PRICE, SHIPPING FROM `PRODUCTS`";
$result = mysql_query($query);
if(mysql_data_seek($result, $rowNumber)) {
// The result set has indeed at least $rowNumber rows
$row = mysql_fetch_assoc($result);
echo $row['ID'];
echo $row['STOCK'];
// ... etc ....
}
else {
echo "No such row!";
}
}
No need to hit the database six times! Of course you need to add error handling.
Btw. is the parameter idNum the same as the ID of the record in the database? If so, you can even further simplify:
function refreshCurrentProduct() {
$dbh=mysql_connect ("DATABASE","USER", "PASS") or die('I cannot connect to the database because:'. mysql_error());
mysql_select_db("TABLE");
// If $_GET['idNum'] is not a number use 0
$id = is_numeric($_GET['idNum']) ? $_GET['idNum'] : 0;
$query = "SELECT ID, STOCK, MYNAME, DESCRIPTION, PRICE, SHIPPING FROM `PRODUCTS` WHERE ID = $id";
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print";
return;
}
$row = mysql_fetch_assoc($result);
echo $row['ID'];
echo $row['STOCK'];
// ... etc ....
}
Take a look at call_user_func.
$functionName = $_GET[ 'func' ];
if( in_array( $functionName, $allowedFunctions ) && function_exists( $functionName ) )
{
call_user_func($functionName);
}
Also, if I'm reading your code right, you could get all of the info in a single query:
$query = "SELECT `ID`,`STOCK`,`MYNAME`,`DESCRIPTION`,`PRICE`,`SHIPPING` FROM `PRODUCTS`";
$result = mysql_query($query) or die('Query failed:'.mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$ID=$row['ID'];
//etc.
}
Your $IDNUM variable is outside the scope of your function. You either need to pass that into your function as a variable or you should be able to set it within the function by setting it inside.
function refreshCurrentProduct() {
$IDNUM = $_GET[ 'idNum' ];
...
}

Categories