How can I run a SELECT query which picks an ID which I use to delete a row in another table with that ID and later delete the row of that ID in its own table?
My code so far:
$sqel = "SELECT fldRadioCampID FROM tblradiocamp WHERE fldBestelID = '$urlIDbon' AND fldSpotnaam = '$urlDelSpotnaam'";
$result = mysql_query($link, $sqel);
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_assoc($result)) {
$sqeldelreg = "DELETE FROM tblradioregio WHERE fldRadiocampRegID=" . $row['fldRadioCampID'];
if (!mysql_query($sqeldelreg)) {
echo "Error: " . $sqeldelreg . "<br>" . mysql_error($link);
}
}
} else {
}
$sqeldel = "DELETE FROM tblradiocamp WHERE fldBestelID='$urlIDbon' AND fldSpotnaam='$urlDelSpotnaam'";
if (!mysql_query($sqeldel)) {
echo "Error: " . $sqeldel . "<br>" . mysql_error($link);
You can create procedure and call it once.
MYSQL
CREATE PROCEDURE `deleteRowById` (in urlDelSpotnaam varchar(64), in urlIDbon varchar(64) )
BEGIN
declare a int(11);
SELECT fldRadioCampID into a FROM tblradiocamp WHERE fldBestelID = urlIDbon AND fldSpotnaam = urlDelSpotnaam;
if a > 0 then
DELETE FROM tblradioregio WHERE fldRadiocampRegID=a;
DELETE FROM tblradiocamp WHERE fldRadioCampID=a;
END IF;
END
PHP
<?php
$sqel = "call deleteRowById('$urlDelSpotnaam','$urlIDbon')";
$result = mysql_query($link, $sqel);
run this query:
DELETE FROM tblradioregio
WHERE fldRadiocampRegID = (SELECT
fldRadioCampID
FROM tblradiocamp
WHERE fldBestelID = '$urlIDbon' AND fldSpotnaam = '$urlDelSpotnaam');
Note that this could also be done using a join instead of the sub-select; that's probably preferable if the subquery can return null:
DELETE FROM tblradioregio
join tblradiocamp b
on (tblradioregio.fldRadiocampRegID = b.fldRadioCampID)
WHERE b.fldBestelID = '$urlIDbon'
AND b.fldSpotnaam ='$urlDelSpotnaam';
Related
I have this php function to check and insert data from text file to database.
//Get All Model
$qModel = oci_parse($c1, "SELECT MODELID, MODEL_NAME FROM MEP_TBL_MODEL WHERE ACTIVE = 'Y' AND LOCATION = 'PCBA' ORDER BY MODELID ASC");
oci_execute($qModel);
while($dModel = oci_fetch_array($qModel))
{
//Configuration
$qDtl = oci_parse($c1, "SELECT * FROM MEP_TBL_MODEL_CONFIGURATION WHERE MODELID_FK = '" . $dModel['MODELID'] . "'");
oci_execute($qDtl);
while($dDtl = oci_fetch_array($qDtl))
{
$modelIDAccept[] = $dDtl['CONFIGURATIONID'];
$dateCode = date($dDtl['DATE_CODE']);
$readRowAfter = date($dDtl['READ_ROW_AFTER']);
$createFromFormat = $dDtl['CREATE_FROM_FORMAT'];
$ipAddress = $dDtl['IP_ADDRESS'];
$status = $dDtl['STATUS'];
if($dDtl['SOURCE'] != "")
{
$source = "\\".$dDtl['SOURCE'];
}
else
{
$source = "";
}
if(empty($ipAddress))
{
$fileAccept = file_get_contents("\\\\192.168.184.13\\Reports\\".$dModel['MODEL_NAME'].$source."\\Accept\\Accept_".$dDtl['MODEL_CODE']."_".$dateCode."_".$dDtl['TS_CODE'].".txt");
$linesAccept = explode("\n",$fileAccept);
$rowsintimespanAccept = 0;
for($i = $readRowAfter; $i < count($linesAccept); $i++)
{
$dateobjAccept = DateTime::createFromFormat($createFromFormat, $linesAccept[$i]);
if($dateobjAccept < $toDateTime && $dateobjAccept > $fromDateTime)
{
$rowsintimespanAccept++;
$logDate = $dateobjAccept->format('Y-m-d H:i:s');
//I put select query and insert here but it so slow.
$qChk = oci_parse($c1, "SELECT * FROM MEP_TBL_OUTPUT_DETAILS WHERE MODELID_FK = '" . $dModel['MODELID'] . "' AND RUNNING_DATE = TO_DATE('$logDate', 'YYYY-MM-DD hh24:mi:ss') AND TS_CODE = '" . $dDtl['TS_CODE'] . "' AND SHIFT = 'Morning' AND QUANTITY_STATUS = 'OK' AND CONFIGURATIONID_FK = '" . $dDtl['CONFIGURATIONID'] . "'");
oci_execute($qChk);
if(oci_fetch($qChk) > 0)
{
}
else
{
$qInsert = oci_parse($c1, "INSERT INTO MEP_TBL_OUTPUT_DETAILS(MODELID_FK, RUNNING_DATE, QUANTITY_STATUS, TS_CODE, SHIFT, CONFIGURATIONID_FK) VALUES('" . $dModel['MODELID'] . "', TO_DATE('$logDate', 'YYYY-MM-DD hh24:mi:ss'), 'OK', '" . $dDtl['TS_CODE'] . "', 'Morning', '" . $dDtl['CONFIGURATIONID'] . "')");
oci_execute($qInsert);
}
}
}
$totalAccept[] = $rowsintimespanAccept;
}
}
}
When I tried to run the code, I got very slow loading the page and sometimes it show me time out execution.
My question, is there any way to make the query fast maybe inside or outside the loop? I knew it slow because when I remove the select and insert query, the load page is only 3-4 seconds.
If I've read your code correctly, what you're after is a single MERGE statement that you can run on the database. I don't know PHP, so I can't give you how it should be called, but I can give you the SQL statement to run:
MERGE INTO mep_tbl_output_details tgt
USING (SELECT mtm.modelid,
mtm.model_name,
mtmc.configurationid,
mtmc.date_code,
mtmc.read_row_after,
mtmc.create_from_format,
mtmc.ip_address,
mtmc.status,
mtmc.ts_code
FROM mep_tbl_model mtm
INNER JOIN mep_tbl_model_configuration mtmc ON mtm.modelid = mtmc.modelid_fk
WHERE mtm.active = 'Y'
AND mtm.location = 'PCBA') src
ON (tgt.modelid_fk = src.modelid
AND tgt.ts_code = src.ts_code
AND tgt.configurationid_fk = src.configurationid
AND tgt.runningdate = :log_date
AND tgt.shift = 'Morning'
AND tgt.quantity_status = 'OK')
WHEN NOT MATCHED THEN
INSERT (tgt.modelid_fk, tgt.running_date, tgt.quantity_status, tgt.ts_code, tgt.shift, tgt.configuration_fk)
VALUES (src.modelid, :log_date, 'OK', src.ts_code, 'Morning', src.configurationid);
This does the join you were reinventing with your loops, links it back to the table you're trying to insert into, and only inserts a row if it doesn't already exist in the table.
You would need to write the PHP code to execute this, having passed the log_date in as a bind variable.
By binding the variable, you allow the database to skip the hard parse (i.e. finding out the best way to execute the query), which saves time.
By not fetching data and manually looping round before selecting more data and working out if you need to do the insert, you skip a whole lot of context switching and pulling/pushing data across the network. Let the database do the heavy lifting; it's what it's designed to do!
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 have a php script for bulk update, in my database exists 90,585 rows but only update 85,282 rows, and i don't know why, this is my script:
//limit the select to 100
//Bulk update is very slow, is you set a limit very high server crash
$limit = 100;
//$messages = array();
$updated_posts = 0;
//maybe there are better solutions for this
for ($i=0;$i<=$totalMsg;$i+=$limit)
{
$get_posts = mysqli_query($conn,
"SELECT id_msg, body
FROM " . $to_prefix ."messages
WHERE id_msg != 0
LIMIT " . $i ."," . $limit);
//The post Array
$messages = array();
while($row = mysqli_fetch_assoc($get_posts))
{
$messages[$row['id_msg']] = array(
'body' => fixBBCTags($row['body']),
);
}
//update data!, good luck!!
bulkUpdate($conn,$to_prefix."messages","id_msg","body",$messages);
$updated_posts += mysqli_affected_rows($conn);
}// for loop
this is the bulkUpdate() function:
function bulkUpdate($conn, $table, $id_column, $update_column, array &$idstovals)
{
global $error;
//prepare the Bulk Update SQL
$sql = "update " . $table . " set " . $update_column . " = CASE " . $id_column ;
foreach($idstovals as $id => $val)
{
$sql .= " WHEN " . "'" . $id . "'" . " THEN " . "'" . mysqli_real_escape_string($conn,$val[$update_column]) . "'" . " \n";
}
$sql .= " END
WHERE " . $id_column. " in (" . implode(',', array_keys($idstovals)) . ")";
//reset the array
//$idstovals=array();
//try update the bulk
$update = mysqli_query($conn,$sql);
if(mysqli_error($conn))
$error = mysqli_error($conn);
}
All the rows must be updated, there are better solution for this?
Regards.
When you wrote the same data in a row, MySQL do not write this record
MariaDB [test]> create table r (id integer, PRIMARY KEY (id) );
Query OK, 0 rows affected (0.15 sec)
MariaDB [test]> insert into r (id) VALUES (1),(2),(3);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
MariaDB [test]> update r set id=4 where id=1;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
MariaDB [test]> update r set id=4 where id=4;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 1 Changed: 0 Warnings: 0
Here my second try,
UPDATE updatetable u
LEFT JOIN reftable r ON r.id = p.id
SET u.updatecol = r.refcol
WHERE r.id_msg !=0 ;
Or you build a array in PHP with id (PRIMARY KEY) and new values. So you can generate a bulk INSERT with ON DUPLICATE KEY UPDATE like this
INSERT INTO mytable (id,col) VALUES
(1,'new val'),
(2,'new val'),
(3,'new val'),
(66,'new val'),
...
(80000,'new val for id 80000')
ON DUPLICATE KEY UPDATE col= VALUES(col);
Sorry am late, here my Answer.
Here is a Sample. I h dont test it. It is importent that the Column id_msg is the PRIMARY KEY or have a unique INDEX.
//limit the select to 100
//Bulk update is very slow, is you set a limit very high server crash
$limit = 100;
$messages = array();
$updated_posts = 0;
$get_posts = mysqli_query($conn,
"SELECT id_msg, body FROM " . $to_prefix ."messages WHERE id_msg != 0");
while($row = mysqli_fetch_assoc($get_posts))
{
$messages[] = "('".$row['id_msg'] ."','"
.mysqli_real_escape_string(fixBBCTags($row['body'])) ."')";
}
$sql_pre = "INSERT INTO ".$to_prefix.".messages (id_msg,message) VALUES "
$sql_post = " ON DUPLICATE KEY message = VALUE(message)"
$sql = "";
$sep = "";
$cnt = 0;
foreach($messages as $msg)
{
$sql = $sep . $msg;
$sep = ",";
if ($cnt++ % $limit) {
mysqli_query($conn,$sql_pre . $sql . $sql_post);
$pre = "";
}
}
// Write the Rest if one
if ( $sql <> "" ) {
mysqli_query($conn,$sql_pre . $sql . $sql_post);
}
I am using PHP PDOs to parse the results I am receiving from MySQL queries against a database. I am now running into an issue with running out of allocated memory. Any suggestions on how to improve the efficiency of my code or another more efficient way to handle query results other than parsing PDOs? Thanks.
Here is my code (which will return whether or not a DB has referential integrity):
function generateDSN($host, $dbname)
{
return 'mysql:host='. $host . ';dbname=' . $dbname;
}
$dbName = $argv[2];
//Used for query construction
$dsn = generateDSN($argv[1], $argv[2]);
//create DSN
$link = new PDO($dsn, "username", "password");
//Connect to the database
//PDO($dsn, username, password)
if ($link->connect_error)
{
die("Connection failed: " . $link->connect_error);
}
else
{
echo "Connected successfully\n";
}
//validate database connection
$query = "SELECT TABLE_CONSTRAINTS.TABLE_NAME, KEY_COLUMN_USAGE.COLUMN_NAME, KEY_COLUMN_USAGE.REFERENCED_TABLE_NAME, KEY_COLUMN_USAGE.REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS RIGHT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ON INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME = INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME WHERE INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME <> 'PRIMARY' AND INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY' AND INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_SCHEMA = '".$dbName."';";
//Create query to return list of tables with foreign keys
/* Query return format:
+--------------+------------------------+-----------------------+------------------------+
| TABLE_NAME | COLUMN_NAME | REFERENCED_TABLE_NAME | REFERENCED_COLUMN_NAME |
+--------------+------------------------+-----------------------+------------------------+
*/
$result = $link->query($query);
//Get query results
$x = 0;
$tableA = [];
$tableB = [];
//Create arrays to hold data from FK queries
while($tables = $result->fetch(PDO::FETCH_ASSOC))
{
$test[] = $tables;
$assoc = $test[$x];
//assign assoc[] the value of $query (will iterate through query table row by row)
$tableName = $assoc['TABLE_NAME'];
$columnName = $assoc['COLUMN_NAME'];
$refTableName = $assoc['REFERENCED_TABLE_NAME'];
$refColumnName = $assoc['REFERENCED_COLUMN_NAME'];
//get data values for each column
$fkQueryA = "SELECT DISTINCT " . $columnName . " FROM " . $dbName . "." . $tableName . " ORDER BY ".$columnName." ;";
$fkQueryB = "SELECT DISTINCT " . $refColumnName . " FROM " . $dbName . "." . $refTableName . " ORDER BY ".$refColumnName." ;";
//A -- Table with column that is the foreign key
//B -- Table with column that the foreign key references
$resultA = $link->query($fkQueryA);
$resultB = $link->query($fkQueryB);
//Get query results
while($var = $resultA->fetchColumn())
{
$tableA[] = $var;
}
//Push query results to table
while($vari = $resultB->fetchColumn())
{
$tableB[] = $vari;
}
//Push query results to table
$x++;
//increment counter to move through $tables
}
$resultCompAB = array_diff($tableA, $tableB);
//return array with all values of A that are not in B
if(empty($resultCompAB))
{
echo "Database ".$dbName." has referential integrity.";
}
else
{
echo "Orphan Values in database ".$dbName.": \n";
array_diff($tableB, $resultCompAB);
}
//print the results
Instead of the array_diff and storing GIGANT php arrays, you should get it with a Query.
This query, will give you values of A that are not in B:
$tableName = $assoc['TABLE_NAME'];
$columnName = $assoc['COLUMN_NAME'];
$refTableName = $assoc['REFERENCED_TABLE_NAME'];
$refColumnName = $assoc['REFERENCED_COLUMN_NAME'];
$sql = "SELECT * FROM {$tableName} LEFT JOIN {$refTableName}
ON {$tableName}.{$columnName} = {$refTableName}.{$refColumnName}
WHERE {$refTableName}.{$refColumnName} IS NULL
";
That's the function which I'm using to print the contents of 'username' table:
function showtable()
{
ob_start();
$db = new PDO("sqlite:test.db");
$query = "SELECT * FROM " . $_SESSION['username'] . " ORDER BY `a` DESC;";
$result = $db->prepare($query);
$result = $db->query($query);
print "<table>";
print "<tr><td>First Column</td><td>Second Column</td><td>Third column</td></tr>";
foreach ($result as $row)
{
print "<tr><td>" . $row['a'] . "</td><td>" . $row['b'] . "</td><td>Here stays the button</td></tr>";
}
print "</table>";
unset($db);
ob_end_flush();
}
So, how should look a function so when creating each row of the html table, a button for updating the corresponding sqlite table row is inserted in the third cell (named 'Here stays the button' for easier reading)? I'm calling my function when opening the test.php (with added required_once('functions.php')) file in main browser window, nothing special in that.
That's the UPDATE query:
$query = "UPDATE " . $_SESSION['username'] . " SET `c` = '1'" . " WHERE `a` = " . $row['a'] . ";";
a column is integer primary key
b column is text
c column is integer, all fields hold 0 value
P.S. Don't talk about AJAX, I'm not ready for it (and don't like it, a lot of pages that use AJAX lag the browser). Just asking for ideas about a simple php function, that adds UPDATE TABLE functionality through buttons for each row.
Thanks in advance :)
What is the updating for? what will happen if C = 1?
anyway for your question, my suggestion is to use an anchor tag.
i.e
in the "Here stays the button" will be Update
in your test.php
if($_GET['a_new'] != '')
{
$query = "UPDATE " . $_SESSION['username'] . " SET `c` = '1'" . " WHERE `a` = ".$_GET['a_new']."";
}
p.s you have excess ";" in your query. you only add the query on the end of the query statement not inside it i.e $sql = "select * from"; not $sql = "select * from;";