How to delete/remove a specific table row in mySQL using php? - php

I already have this code:
<?php
if ($quantity == 0){
$prd_name = " ";
$colors = " ";
$sizes = " ";
$quantity = " ";
$price = " ";
$TIP = " ";
$TPA = " ";
$cost = " ";
$amount = " ";
$query ="DELETE FROM orders WHERE quantity='0'";
}
?>
But it still makes a table row entry.
What I am trying to do is when the inputed number of quantity is 0 then the table row will be deleted. Please bear with me for I'm new in php and mySQL coding.

You forgot to execute the query. It should be
$query = mysql_query("DELETE FROM orders WHERE quantity='0'");

Once run the query by removing Quotes to 0 If it's a number
<?php
if($quantity==0)
{
$query = "DELETE FROM orders WHERE quantity = 0 ";
mysql_query($query);
}
?>

<?php
if($quantity==0)
{
$query="Delete from orders where quantity=0";
mysql_query($query);
}
?>

Related

PHP Search query result ORDER BY not working

I have this code to search database. It now works perfectly but i want to change the order of which it displays. Below is my code.
if (isset($_GET["mainSearch"]))
{
$condition = '';
$query = explode(" ", $_GET["mainSearch"]);
foreach ($query as $text)
{
$condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
$condition = substr($condition, 0, -4);
$order = "ORDER BY quiz_id DESC";
$sql_query = "SELECT * FROM questions WHERE " . $condition;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;
$result = $db->query($sql_query);
$resultCount = $db->querySingle($sql_query_count);
if ($resultCount > 0)
{
if ($result)
{
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
echo '<div class="quesbox_3">
<div class="questitle">
<h2>'.$row["question"].'</h2>
</div>
<div class="quesanswer">'.$row["answer"].'</div>
</div>';
}
}
}
else
{
echo "No results found";
}
}
I want the ORDER of which result show to be from bottom to top. Please how can i add this properly as current code isn't working.
Your putting the order by on the count() query, which doesn't do much really.
$sql_query = "SELECT * FROM questions WHERE " . $condition;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;
Try
$sql_query = "SELECT * FROM questions WHERE " . $condition. ' '. $order;
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition ;
Your $order is in your count query alone. Add to your $sql_query
$sql_query = "SELECT * FROM questions WHERE " . $condition . ' '. $order;
Give 1 space in this string
$order = " ORDER BY quiz_id DESC ";
It is not showing you because if you echo your query than it will show like this
SELECT COUNT(*) as count FROM questions WHERE question LIKE '%test%'ORDER BY quiz_id DESC
You can see in this echo query there is a no space between ORDER and %test%
do Like this it will helps you.
Query Space issues. can you try with this query
$sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition .' '. $order;

Query stopped running instead of inserting zero values

We have this MySQL query where we want to find the date_time and price_open from price table and update these two values into the price_datetime and price_open columns in comment table:
UPDATE comment AS fc
INNER JOIN price AS p
ON p.ticker_id = fc.ticker_id
AND p.date_time =
( SELECT pi.date_time
FROM price AS pi
WHERE pi.ticker_id = fc.ticker_id
AND pi.date_time >= fc.date_time
ORDER BY pi.date_time ASC
LIMIT 1
) SET
fc.price_datetime = p.date_time,
fc.price_open = p.price_open;
Which we converted to PHP+MySQL hoping for a more efficiency and much faster process:
<?php
ob_flush();
flush();
usleep(160);
$tickers = array();
$stmt = $mysqli->prepare("SELECT ticker_id, date_time FROM flaggedcomment order by ticker_id, date_time");
$stmt->execute(); //Execute prepared Query
$stmt->bind_result($tid, $dt);
$arr_index = 0;
while ($stmt->fetch() ) {
$tickers[$arr_index] = array();
$tickers[$arr_index]["id"] = $tid;
$tickers[$arr_index]["dt"] = $dt;
$arr_index++;
}
/* free result set */
$stmt->free_result();
$record_index = 0;
$flaggedcomment_index = 0;
$sql = "";
// get total tickers
$total_tickers = count($tickers);
echo "Total records: " . $total_tickers . "<br />";
foreach ($tickers as $ticker) { //fetch values
$stmt = $mysqli->prepare("SELECT price_open, date_time FROM price WHERE ticker_id =? AND date_time >=? ORDER BY date_time ASC LIMIT 1;");
$stmt->bind_param("is",$ticker["id"], $ticker["dt"]); // two params: one is integer, and other one is string
$stmt->execute(); //Execute prepared Query
$results = $stmt->get_result();
$myrow = $results->fetch_row();
$set_string = "SET";
// bind values
$price_open = $myrow[0];
$date_time = $myrow[1];
// set initial insert query value
$set_string .= " price_datetime='". $date_time ."'";
$set_string .= ", price_open=". $price_open;
$set_string .= " WHERE ticker_id=". $ticker["id"] ." AND date_time='" . $ticker["dt"] ."'";
if($set_string != ""){
$sql .= "UPDATE flaggedcomment ". $set_string . ";";
}
$idx = $record_index + 1;
if(($record_index + 1) % 100 == 0){
?>
<script>
$('#page-wrap > h1').html("Processing Ticker id #" + <?= $ticker["id"]; ?> + " - Record #" + <?= $idx; ?>);
</script>
<?php
ob_flush();
flush();
usleep(160);
}
$record_index++;
/* free result set */
$stmt->free_result();
} // end while fetch ticker id
$update_flaggedcomment_qry = "LOCK TABLES flaggedcomment WRITE; ". $sql . "UNLOCK TABLES; ";
echo $update_flaggedcomment_qry;
//echo "<br />";
if ($mysqli->multi_query($update_flaggedcomment_qry)) {
// nothing
} else {
echo "Error updating record: " . $mysqli->error . "<br />";
$mysqli->close();
exit;
}
echo "<span style='color:blue;'> <b> Done. </b> </span>";
ob_end_flush();
exit;
?>
Using the MySQL query, if there's no match of ticker_id and date_time from both tables, the fc.price_datetime and fc.price_open columns will show 0000-00-00 00:00:00 and 0.00 values. However, when executing the PHP code, instead of inserting the zero values, it will stop when it encounters its very first "no matching" of ticker_id and date_time and cannot continue. We've spent a long time figuring out on how to fix it, unfortunately, none of the ways we use can fix this.
Any help from the community is definitely much appreciated.
Thank you. :)
You do not check if there is a record returned from price . Hence your code just tries picking the first and second elements of the result array when that array is null. You then likely land up with a statement trying to assign blank to each of the price_datetime and price_open fields. With the price_datetime you have quotes around the empty value and mysql will probably cope with this, but for price_open you do not have quotes around the expected numeric value. Hence you will land up with an invalid update statement (some like the following):-
UPDATE flaggedcomment price_datetime='', price_open= WHERE ticker_id=123 AND date_time='2016-01-01 00:00:00';
As you are executing multiple SQL statements at once to do the updates, I expect that it won't execute any after the invalid statement.
A quick play with your code and the following should work. This checks the returned row and if one isn't found it just uses the default (zero like) values for the 2 fields you want to update.
<?php
ob_flush();
flush();
usleep(160);
$tickers = array();
$stmt = $mysqli->prepare("SELECT ticker_id, date_time FROM flaggedcomment order by ticker_id, date_time");
$stmt->execute(); //Execute prepared Query
$stmt->bind_result($tid, $dt);
$arr_index = 0;
while ($stmt->fetch() )
{
$tickers[$arr_index] = array();
$tickers[$arr_index]["id"] = $tid;
$tickers[$arr_index]["dt"] = $dt;
$arr_index++;
}
/* free result set */
$stmt->free_result();
$record_index = 0;
$flaggedcomment_index = 0;
$sql = "";
// get total tickers
$total_tickers = count($tickers);
echo "Total records: " . $total_tickers . "<br />";
foreach ($tickers as $ticker)
{ //fetch values
$stmt = $mysqli->prepare("SELECT price_open, date_time FROM price WHERE ticker_id =? AND date_time >=? ORDER BY date_time ASC LIMIT 1;");
$stmt->bind_param("is",$ticker["id"], $ticker["dt"]); // two params: one is integer, and other one is string
$stmt->execute(); //Execute prepared Query
$results = $stmt->get_result();
if ($myrow = $results->fetch_assoc())
{
$price_open = $myrow['price_open'];
$date_time = $myrow['date_time'];
}
else
{
$price_open = 0.00;
$date_time = "0000-00-00 00:00:00";
}
$sql .= "UPDATE flaggedcomment SET";
$sql .= " price_datetime='". $date_time ."'";
$sql .= ", price_open=".$price_open;
$sql .= " WHERE ticker_id=". $ticker["id"] ." AND date_time='" . $ticker["dt"] ."';";
$idx = $record_index++;
if(($record_index + 1) % 100 == 0)
{
?>
<script>
$('#page-wrap > h1').html("Processing Ticker id #" + <?= $ticker["id"]; ?> + " - Record #" + <?= $idx; ?>);
</script>
<?php
ob_flush();
flush();
usleep(160);
}
$record_index++;
/* free result set */
$stmt->free_result();
} // end while fetch ticker id
$update_flaggedcomment_qry = "LOCK TABLES flaggedcomment WRITE; ". $sql . "UNLOCK TABLES; ";
echo $update_flaggedcomment_qry;
//echo "<br />";
if ($mysqli->multi_query($update_flaggedcomment_qry)) {
// nothing
}
else
{
echo "Error updating record: " . $mysqli->error . "<br />";
$mysqli->close();
exit;
}
echo "<span style='color:blue;'> <b> Done. </b> </span>";
ob_end_flush();
exit;
?>
However I suspect that looping around the result of one query and doing another query for each row in php will be slower than a well constructed single update query.
If you do want to loop around the results like you are doing now it may be quicker to create a tmp table and insert the rows to that (as you can insert hundreds of rows with a single statement) and then update your flaggedcomment table with a single update statement that joins it to the tmp table
EDIT - If you can post the table declares and a bit of sample data I will have an attempt at doing it in a single SQL statement.
A first attempt (untested) would be:-
UPDATE comment AS fc
INNER JOIN price AS p
ON p.ticker_id = fc.ticker_id
INNER JOIN
(
SELECT *
FROM
(
SELECT fc.ticker_id,
MIN(pi.date_time) AS date_time
FROM comment AS fc
INNER JOIN price AS pi
ON pi.ticker_id = fc.ticker_id
AND pi.date_time >= fc.date_time
GROUP BY fc.ticker_id
) sub1
) sub0
ON p.ticker_id = sub0.ticker_id
AND p.date_time = sub0.date_time
SET fc.price_datetime = p.date_time,
fc.price_open = p.price_open;
This is using the extra seemingly redundant sub query to hopefully bypass a MySQL restriction on updating a table that is also used in a subquery.

I want to use two where conditions in php to get data from mysql

My problem is this:
<?php
// Connect to database server
mysql_connect("localhost", "root", "abcabc") or die (mysql_error ());
// Select database
mysql_select_db('iite') or die(mysql_error());
// Get data from the database depending on the value of the id in the URL
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
echo'<h1>'. $row['title'].'</h1>';
echo'<h1>'. $row['price'].'</h1>';
}
// Close the database connection
mysql_close();
?>
I want to show related posts, for this I need to insert this:
$sql = "SELECT * FROM table1 where title like '%keyword%' limit 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["price"]. " " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
so how can I insert the related post part near
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"];
and how to echo?
Thanks
You can use OR or AND for combining different where conditions(according to requirement) in query :
Ex;
$strSQL = "SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5";
$strSQL = mysql_query(SELECT * FROM table1 WHERE id=" . $_GET["id"] ." OR title like '%keyword%' limit 5) or die(mysql_error());
$row_strSQL = mysql_fetch_assoc($strSQL );
$totalRows_strSQL = mysql_num_rows($strSQL );
if ($result->totalRows_strSQL > 0) {
// output data of each row
while($row_strSQL= $result->fetch_assoc()) {
echo "id: " . $row_strSQL["id"]. " - Name: " . $row_strSQL["price"]. " " . $row_strSQL["title"]. "<br>";
}
} else {
echo "0 results";
}
You don't need two seperate queries for that at all. Just use the OR operator in ur where clause like Where id=" . $_GET['id']." or title like '%keyword%'

Sum Columns in PHP table

I have an index.php with various SQL queries which helps me find the balances of the respective accounts. This is a TRIAL BALANCE so I need to SUM all the amount in the Debit Column and SUM all the amount in the Credit Column so that I can Tally both of them. Please help me with the SUM. All values are echoed to a PHP table.
index.php
<?php
echo "<table border='1'>";
echo "<tr><th width='150'>Account</th><th width='200'>Debit</th><th width='200'>Credit</th></tr>";
echo "<tr><th align='left'>Cash & Bank</th></tr>";
//List the Banks first with their respective balances.
$bank_sql = "SELECT * FROM bank";
$bank_query = mysqli_query($conn, $bank_sql);
while ($bank_result = mysqli_fetch_array($bank_query)){
$bank_name = $bank_result['name'];
$sql= "SELECT SUM(amount) FROM account WHERE (mode='$bank_name' AND status='completed') AND (type='p' OR type='r')";
$sql_query = mysqli_query($conn, $sql);
while($sql_result = mysqli_fetch_array($sql_query)){
$sql_value = $sql_result['SUM(amount)'];
}
$sql1 = "SELECT SUM(amount) FROM account WHERE (mode='$bank_name' AND status='completed') AND (type='s' OR type='pa')";
$sql1_query = mysqli_query($conn, $sql1);
while($sql1_result = mysqli_fetch_array($sql1_query)){
$sql1_value = $sql1_result['SUM(amount)'];
}
echo "<tr><td>".$bank_name."</td>";
if ($sql_value > $sql1_value){
echo "<td align='right'>AED " . number_format(($sql_value - $sql1_value),2) . "</td><td>&nbsp</td>";
}
elseif ($sql1_value > $sql_value) {
echo "<td>&nbsp</td><td align='right'>AED " . number_format(($sql1_value - $sql_value),2) . "</td>";
}
else {
echo "<td>&nbsp</td><td>&nbsp</td>";
}
}
echo "</tr></table>";
}
?>
Try the below query
SELECT SUM(amount) FROM ht_account WHERE mode='$bank_name' AND status='completed' AND type IN('sale','purchase','reciept','payment')
A quick way to do it would be.
$sql3="select column1,column2 from yourtable where ..condition";
$sumofcolumn1;
$sumofcolumn2;
while($sql3_result = mysqli_fetch_array($sql3))
{
$sumofcolumn2+=$sql3_result['column2'];
$sumofcolumn1+=$sql3_result['column1'];
}
echo $sumofcolumn1.' '.$sumofcolumn2

PHP SQL database query error message

Is there anything wrong with this SQL code? I got it from a tutorial, but it's returning the following error message
Database query failed: You have an
error in your SQL syntax; check the
manual that corresponds to your MySQL
server version for the right syntax to
use near 'LIMIT 1' at line 1
function get_subject_by_id($subject_id) {
global $connection;
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE id=" . $subject_id ." ";
$query .= "LIMIT 1";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
// if no rows are returned, fetch array will return false
if ($subject = mysql_fetch_array($result_set)){
return $subject;
} else {
return NULL;
}
}
Best to echo the query and see what it looks like.
Probably $subject_id contains no value or an invalid value. If $subject_id is a string, you should escape it (using mysql_real_escape_string) and put it inside quotes in the query.
[Edit]
You know you can put enters in strings too, right?
// More readable
$query = "
SELECT *
FROM subjects
WHERE id = $subject_id
LIMIT 1";
$query .= "where id=" . $page_id . " ";
Needs to be put within single quotes. Replace the above statement by
$query .= "where id='" . $page_id . "' ";
Frankly, it's impossible to say what is exactly wrong with this code, not knowing what values are substituted in the query in place of variables.
Apart from that, the code in question may be subject to SQL injection attacks.
If I may put together other suggestions that will make sure no error is ever generated with this code:
function get_subject_by_id($subject_id) {
global $connection;
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE id='" . mysql_real_escape_string($subject_id) ."' ";
// note the quotes and escaping wrapper
$query .= "LIMIT 1";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
// if no rows are returned, fetch array will return false
if ($subject = mysql_fetch_array($result_set)) {
return $subject;
} else {
return NULL;
}
}
Additionally, using global variables is a bad practice nowadays, so I suppose the example you're using is quite outdated.
Try to use mysql_real_escape_string()
function get_subject_by_id($subject_id) {
global $connection;
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "WHERE id='" . $subject_id ."' "; //You need single quotes
$query .= "LIMIT 1";
$result_set = mysql_query($query, $connection);
confirm_query($result_set);
// REMEMBER:
// if no rows are returned, fetch_array will return false
if ($subject = mysql_fetch_array($result_set)) {
return $subject;
} else {
return NULL;
}
}
$query .= "WHERE id='" . $subject_id ."' "; //work
$query .= "WHERE id=" . $subject_id ." "; //not work

Categories