I have a mySQL database table called stock which holds a stock record on items for sale. When querying the database using PHP I have no issue, but when I try to do it through Wordpress it doesn't work.
my PHP is as follows
// Query the stock level
function QueryStock($cat) {
$query = "SELECT * FROM stock";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $cat) {
$catno=$row[0];
$supplier=$row[1];
$itemname=$row[2];
$category=$row[3];
$price=$row[4];
$stock=$row[5];
}
}
mysql_close($db_server);
echo "There are " . $stock . " bears";
}
$cat in the function attribute is the catalogue number of the item I am querying and the output is "There are 2 bears".
I put this in Wordpress and the webpage hangs. Then through Google searching, I found out about the $wpdb object being used by Wordpress at designmodo.com. So with some code condensing too, I changed it to...
function QueryStock($cat) {
$query = "SELECT * FROM stock WHERE catno = " . $cat;
global $wpdb;
$row = $wpdb->get_row($query, ARRAY_N);
$catno == $row[0];
$itemname = $row[2];
$price = $row[4];
$stock = $row[5];
echo "There are " . $stock . " bears";
}
Now the output is "There are bears" (missing the $stock value). I have been doing loads of Google searching to get where I am and I am having problems understanding it. Where am I going wrong?
Try:
function QueryStock($cat) {
$query = "SELECT * FROM stock WHERE catno = " . $cat;
global $wpdb;
$row = $wpdb->get_row($query);
$catno = $row->catno; //Column name in table
$itemname = $row->itemname; //Column name in table
$price = $row->price; //Column name in table
$stock = $row->stock; //Column name in table
echo "There are " . $stock . " bears";
}
Also, I would advise against using "SELECT *". Try to query only for the columns used. This is better for performance.
Edit: saw a typo. You had "$catno == $row..." in your code. You should only use one "="
Eureka!!!,
It's often something missed, and it was in the MySQL query.
The query should be SELECT * FROM stock WHERE catno = '$cat' making $query = "SELECT * FROM stock WHERE catno = '$cat'";
I have taken on board the "SELECT *" issue #eckes and #rickonline pointed out, went for separate queries and used $wpdb->get_var().
Working coding is..
function QueryStock($cat) {
$query1 = "SELECT catno FROM stock WHERE catno = '$cat'";
$query2 = "SELECT itemname FROM stock WHERE catno = '$cat'";
$query3 = "SELECT price FROM stock WHERE catno = '$cat'";
$query4 = "SELECT stock FROM stock WHERE catno = '$cat'";
global $wpdb;
$catno = $wpdb->get_var($query1);
$itemname = $wpdb->get_var($query2);
$price = $wpdb->get_var($query3);
$stock = $wpdb->get_var($query4);
echo "There are " . $stock . " bears";
}
Related
I have a column in a table that I would like to add up and return the sum. I have a loop, but it's not working.
while ($row = mysql_fetch_assoc($result)){
$sum += $row['Value'];
}
echo $sum;
You can completely handle it in the MySQL query:
SELECT SUM(column_name) FROM table_name;
Using PDO (mysql_query is deprecated)
$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];
Or using mysqli:
$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['ColumnName'];
}
echo $qty;
Try this:
$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];
Let us use the following image as an example for the data in our MySQL Database:
Now, as the question mentions, we need to find the sum of a particular column in a table. For example, let us add all the values of column "duration_sec" for the date '09-10-2018' and only status 'off'
For this condition, the following would be the sql query and code:
$sql_qry = "SELECT SUM(duration_sec) AS count
FROM tbl_npt
WHERE date='09-10-2018' AND status='off'";
$duration = $connection->query($sql_qry);
$record = $duration->fetch_array();
$total = $record['count'];
echo $total;
MySQL 5.6 (LAMP) . column_value is the column you want to add up. table_name is the table.
Method #1
$qry = "SELECT column_value AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
while ($rec = $db->fetchAssoc($res)) {
$total += $rec['count'];
}
echo "Total: " . $total . "\n";
Method #2
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
$rec = $db->fetchAssoc($res);
$total = $rec['count'];
echo "Total: " . $total . "\n";
Method #3 -SQLi
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $conn->query($sql);
$total = 0;
$rec = row = $res->fetch_assoc();
$total = $rec['count'];
echo "Total: " . $total . "\n";
Method #4: Depreciated (don't use)
$res = mysql_query('SELECT SUM(column_value) AS count FROM table_name');
$row = mysql_fetch_assoc($res);
$sum = $row['count'];
$row['Value'] is probably a string. Try using intval($row['Value']).
Also, make sure you set $sum = 0 before the loop.
Or, better yet, add SUM(Value) AS Val_Sum to your SQL query.
$result=mysql_query("SELECT SUM(column) AS total_value FROM table name WHERE column='value'");
$result=mysql_result($result,0,0);
Get Sum Of particular row value using PHP MYSQL
"SELECT SUM(filed_name) from table_name"
$sql = "SELECT SUM(Value) FROM Codes";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
sum = $row['SUM(price)'];
}
echo sum;
I have an Android app that will POST the category variable to my PHP. In my PHP i wand to find the category (column) the buyer is interested in and then in that row concatenate the 3 other columns from that same row. Then save that into a variable which i will echo out.
i realize there are multiple products listed in the same category but that is a different question.
PHP code:
<?php
$conn = mysqli_connect("phpmyadmin.cvw71h2krjrb.us-east-1.rds.amazonaws.com", "phpmyadmin", "phpmyadmin", "Products");
$Category = $_POST["Category"];
//$sql_query = "select Product_Category from Products where Product_Category like '$Category'";
$sql_query = "select concat(Product_Owner_Email,'_',Product_Name,'_', Product_Key_Code) as productkeyword from table where <Product_Category like '$Category'>";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$Product_Owner_Email = $row['Product_Owner_Email'];
$Product_Name = $row['Product_Name'];
$Product_Key_Code = $row['Product_Key_Code'];
}
mysqli_close($conn);
echo $ProductKeyWord;
?>
How can i concatenate 3 columns with MySQL in PHP?
also
On my app the echo back is ""
...................................................................... ANSWER BELOW............................................................
<?php
ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(E_ALL);//This code is used so if i test the PHP in the browser itll tell me any errors or warnings!!
$conn = mysqli_connect("XXXX", "XXXX", "XXXX", "Products");
$Category = $_POST["Category"];
$sql = "SELECT Product_Owner_Email, Product_Name, Product_Key_Code FROM Product_Details WHERE Product_Category LIKE '$Category'
LIMIT 0 , 30";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["Product_Owner_Email"]. "_" . $row["Product_Name"]. "_" . $row["Product_Key_Code"] . " ";
}
} else {
echo "0 results";
}
$conn->close();
?>
the answer actually returns every "product" in the $Category
You can use the below query:
select concat(Product_Owner_Email,'_',Product_Name,'_', Product_Key_Code) as productkeyword from table where <where condition>
I have updated your code, now try this.
$conn = mysqli_connect("phpmyadmin.cvw71h2krjrb.us-east-1.rds.amazonaws.com", "phpmyadmin", "phpmyadmin", "Products");
$Category = $_POST["Category"];
//$sql_query = "select Product_Category from Products where Product_Category like '$Category'";
$sql_query = "select Product_Owner_Email,Product_Name,concat(Product_Owner_Email,'_',Product_Name,'_',Product_Key_Code) as productkeyword from Products where Product_Category like '".$Category."'";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$Product_Owner_Email = $row['Product_Owner_Email'];
$Product_Name = $row['Product_Name'];
$Product_Key_Code = $row['productkeyword'];
}
mysqli_close($conn);
echo $Product_Key_Code;
?>
I want to get an id from browser and display some pictures from the database.
If there is no "display2.php?productid=" found, then I want to display default image.
How can I do that?
Here is my code;
$sql = "SELECT * FROM productlist where productid=".$_GET['productid'];
$result = $mysqli->query($sql);
while($myRow = $result->fetch_array())
{
if(null !==($_GET['productid']==$myRow["productid"])){
echo "<img src=".$myRow["productid"].">";
}
else {
echo "<img src="SELECT productimage FROM productlist where productid = 1;">";
}
}
Now I will make it easier to explain for you...
Check this out;
//This part works without any problem
$sql = "SELECT * FROM productlista where productid=".$_GET['productid'];
$result = $mysqli->query($restwo);
while($myRow = $resulttwo->fetch_array())
{
if(null !==($_GET['productid']==$myRow["productid"])){
echo "<img src=".$myRow["productimage"].">";
}
//This part below (that should be default) does not work...
if (!$_GET){
echo "hello world"; }
Asaph pointed out SQL injection. You should bind the parameter (google it), or at the minimum do this:
$defaultImage = "SELECT * FROM productlist WHERE imageSrc != '' OR IS NOT NULL ORDER BY productid DESC LIMIT 1";
// run the query, get the result, create a variable with default image...
$defaultImageSrc = ''; // what you get from the query result
$_GET['productid'] = preg_replace('#[^0-9]#', '', $_GET['productid']);
$sql = "SELECT * FROM productlist where productid=".$_GET['productid'];
$result = $mysqli->query($sql);
while($myRow = $result->fetch_array()) {
if(!$myRow['imageSrc']) $myRow['imageSrc'] = $defaultImageSrc;
echo '<img src="'.$path.'">';
}
If you want either $_GET['productid'] or the max(productid) when $_GET['productid'] is not set, you can use a ternary to change your sql query
$productid = ! empty($_GET['productid']) ? " WHERE productid = ".(int)$_GET['productid'] : " ORDER BY productid DESC LIMIT 1";
$sql = "SELECT * FROM productlist".$productid
$result = $mysqli->query($sql);
while($myRow = $result->fetch_array())
{
echo "<img src=".$myRow["productimage"].">";
}
so if isset($_GET['productid']) your query would be
SELECT * FROM productlist WHERE productid = (int)$_GET['productid']
but if not the default would be
SELECT * FROM productlist ORDER BY productid DESC LIMIT 1
$myEvents = $wpdb->prefix . 'Events';
$sql = "SELECT COALESCE(max(event_id),0) FROM $myEvents WHERE event_title = 'pd'";
$numb = $wpdb->get_results($sql);
$num = $numb->{'event_id'};
echo $num;
The following code echo'es 0 all the time even though I know it shouldn't. What's wrong?
I have a column in a table that I would like to add up and return the sum. I have a loop, but it's not working.
while ($row = mysql_fetch_assoc($result)){
$sum += $row['Value'];
}
echo $sum;
You can completely handle it in the MySQL query:
SELECT SUM(column_name) FROM table_name;
Using PDO (mysql_query is deprecated)
$stmt = $handler->prepare('SELECT SUM(value) AS value_sum FROM codes');
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sum = $row['value_sum'];
Or using mysqli:
$result = mysqli_query($conn, 'SELECT SUM(value) AS value_sum FROM codes');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);
$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
$qty += $num['ColumnName'];
}
echo $qty;
Try this:
$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];
Let us use the following image as an example for the data in our MySQL Database:
Now, as the question mentions, we need to find the sum of a particular column in a table. For example, let us add all the values of column "duration_sec" for the date '09-10-2018' and only status 'off'
For this condition, the following would be the sql query and code:
$sql_qry = "SELECT SUM(duration_sec) AS count
FROM tbl_npt
WHERE date='09-10-2018' AND status='off'";
$duration = $connection->query($sql_qry);
$record = $duration->fetch_array();
$total = $record['count'];
echo $total;
MySQL 5.6 (LAMP) . column_value is the column you want to add up. table_name is the table.
Method #1
$qry = "SELECT column_value AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
while ($rec = $db->fetchAssoc($res)) {
$total += $rec['count'];
}
echo "Total: " . $total . "\n";
Method #2
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $db->query($qry);
$total = 0;
$rec = $db->fetchAssoc($res);
$total = $rec['count'];
echo "Total: " . $total . "\n";
Method #3 -SQLi
$qry = "SELECT SUM(column_value) AS count
FROM table_name ";
$res = $conn->query($sql);
$total = 0;
$rec = row = $res->fetch_assoc();
$total = $rec['count'];
echo "Total: " . $total . "\n";
Method #4: Depreciated (don't use)
$res = mysql_query('SELECT SUM(column_value) AS count FROM table_name');
$row = mysql_fetch_assoc($res);
$sum = $row['count'];
$row['Value'] is probably a string. Try using intval($row['Value']).
Also, make sure you set $sum = 0 before the loop.
Or, better yet, add SUM(Value) AS Val_Sum to your SQL query.
$result=mysql_query("SELECT SUM(column) AS total_value FROM table name WHERE column='value'");
$result=mysql_result($result,0,0);
Get Sum Of particular row value using PHP MYSQL
"SELECT SUM(filed_name) from table_name"
$sql = "SELECT SUM(Value) FROM Codes";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
sum = $row['SUM(price)'];
}
echo sum;