I am trying to write PHP code to update a value once it exist, and if it doesn't then insert it. Part of this function works which is the insert part however the update doesn't seem to work my code is below:
<?php
$id = $_GET['Track'];
$user = $_GET['User'];
$rating = $_GET['Rating'];
include("connect.php");
$query = "UPDATE `rating` SET `rating` = '$rating' WHERE track_id = '$id' AND user_id = '$user' AND rating_set=NOW()";
$sth = $dbc->query($query);
$rows = $sth->rowCount();
if ($rows == 0) {
$query = "INSERT INTO rating values ('$id','$rating','$user',NOW())";
$results = $dbc->query($query);
$rows = $results->rowCount();
}
/* output in necessary format */
header('Content-type: application/json; charset=utf-8');
echo $_GET['onJSONPLoad'];
echo "(" . json_encode($rows) . ")";
$dbc = null;
?>
Your update query can't work.
You are only updating data where rating_set is exactly NOW(). That will most likely not fit on any data record. You probably only want to use the date part.
you are using NOW() in update query, which gives current time. Which will never be same!!! try removing '....AND rating_set=NOW()' from your update query.
Related
I'm new to both PHP & mySQL, but I suspect some apostrophe related bug here (maybe).
For some reason the first query always seems to return null because the
echo "result: $result\n";
never prints any data. At the first call that is expected, but at the second call the player has been added to the db. My database works in the sense that I can see that rows with correct ids are added to the database (via phpMyAdmin).
Can you help me spot the error?
<?php
require_once('Db.php');
$db = new Db();
// Quote and escape form submitted values
$id = $db->quote($_POST['id']);
$score = $db->quote($_POST['score']);
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = `$id`");
echo "result: $result\n"; // Never prints any data
if($result->num_rows == 0) {
// Row not found. Create it!
$result = $db->query("INSERT INTO `xxxxxx`.`Player` (`id`,`score`) VALUES (" . $id . "," . 0 . ")");
}
?>
First, drop those backticks from id in WHERE clause, otherwise it will take the field name from id column instead of 'id'.
Then you need to fetch data from $result:
$result = $db->query("SELECT id FROM `xxxxxx`.`Player` WHERE id = '$id'");
$row = $result->fetch_array();
echo $row['id'];
Or if there are more rows than one:
while($row = $result->fetch_array())
{
echo $row['id'];
}
You are using backticks in your query for $id. Remove them and try again.
Your query should be
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = $id");
OR
$result = $db->query("SELECT `id` FROM `xxxxxx`.`Player` WHERE `id` = ".$id."");
I'm having a few issues with this silly query, was wondering is it possible to concatenate the following INSERT query inside the IF statement and outside it as well to complete the rest of the query. So I want the $orderid to be insert within the if statement and the rest of the last 3 variables outside the IF
if(isset($_POST['Submit'])){
$orderid=mysql_insert_id();
$sql = mysql_query("SELECT * FROM course WHERE serial='$serial'") or die(mysql_error());
$fetch = mysql_fetch_assoc($sql);
$serial = $fetch['serial'];
$price = $fetch['price'];
mysql_query("INSERT into course_order_detail values ('$orderid','$serial','1','$price')") or die(mysql_error());
}
Oh and $orderid is from the previous insert query written in my code.
Try Like this
if(isset($_POST['Submit'])){
$orderid=mysql_insert_id();
$sql = mysql_query("SELECT * FROM course WHERE serial='$serial'") or die(mysql_error());
$fetch = mysql_fetch_assoc($sql);
$serial = $fetch['serial'];
$price = $fetch['price'];
$in = mysql_query("INSERT into course_order_detail values ('$orderid')") or die(mysql_error());
$new_id = mysql_insert_id();
}
$up = mysql_query("UPDATE course_order_detail SET serial='$serial',quantity='1',price='$price' WHERE orderid = ".$new_id);
You can use a nested insert with select
INSERT `into course_order_detail` SELECT '$orderid', serial, '1', price FROM course WHERE serial='$serial'
BTW sanitize your queries
I am trying to insert to another table the results of a select statement from another table. The select statement works but the insert statement does not work. Please help me.
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
}
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
header("Location:homeclient.php");
?>
You asked for how to do these two as one query.
This is how:
$query = mysql_query("INSERT INTO `client` ( `client_csub_code`, `client_csub_name`, `client_csub_day`, `client_csub_time` ) SELECT `sub_code`, `sub_name`, `sub_day`, `sub_time` FROM `subject` WHERE `code` = '$enrol'");
// I would also add error checking
if ( mysql_errno() )
echo mysql_error();
$query="SELECT * FROM subject WHERE sub_code = '$enrol' ";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$csubject=$row['sub_name'];
$cday=$row['sub_day'];
$ctime=$row['sub_time'];
echo "<strong>". $csubject . "</strong>";
$query = mysql_query("INSERT INTO client (client_csub_code,client_csub_name,client_csub_day,client_csub_time) VALUES ('$enrol','$csubject','$cday','$ctime')");
}
header("Location:homeclient.php");
?>
Try changing to this. Currently your query is outside of your while, it will only run once and the values of $csubject etc are always going to be the last values of your fetched results.
I am trying to write an API with php which will check the values a user has entered and if the trackid and userid are already in the database it will update the rating. However if the track and user id doesn't exist then the API should insert them along with a rating. How can this be done. Please note I keep getting the error:
Call to a member function rowCount() on a non-object
on line 14. Any help will be appreciated.
<?php
$id = $_GET['TrackId'];
$user = $_GET['UserId'];
$rating = $_GET['Rating'];
include("connect.php");
$query = "UPDATE `rating` SET `rating` = '$rating' WHERE track_id = '$id' AND user_id = '$user' AND rating_set=NOW()";
$sth = $dbc->query($query);
$rows = $sth->rowCount();
if ($rows != 2) {
$query = "INSERT INTO `rating` values ('$id','$rating','$user',NOW())";
$results = $dbc->query($query);
$rows = $results->rowCount();
header('Content-type: application/json; charset=utf-8');
echo $_GET['onJSONPLoad'];
echo "(" . json_encode($rows) . ")";
}
else
{
header('Content-type: application/json; charset=utf-8');
echo $_GET['onJSONPLoad'];
echo "(" . json_encode($rows) . ")";
}
$dbc = null;
?>
The error is because your $results is null / false, which is probably due to a failed SQL execution.
Assuming that your $dbc->query($sql) is a wrapper of mysqli_query(), the function will return false on failed query. To debug this behavior, you can var_dump($results).
In the update query part of the condition I am looking for is NOW() which will never be found. So I moved it to the update section of the query instead of the conditional area.
Use the ON DUPLICATE KEY clause
INSERT INTO table (column1, ... )
VALUES (’value1’, ...)
ON DUPLICATE KEY
UPDATE column2 = =value2, ...
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
I want to know how to fetch single row from Oracle in PHP?
Chedck my script-:
I want to fetch single row from ITEM_INFO table & compare that values with variables $sku & $code...Logic I applied which works in Mysql but not working in Oracle...
Each time $sku & $code contains diff. values so I just need to compare them with ITEM_INFO table & if it's matches then update the flag for the same...
$query_fetch = "SELECT ITEM_NAME,SITE_CODE FROM app.ITEM_INFO WHERE ITEM_FLAG = 'N'";
$stmt = oci_parse($conn,$query_fetch);
oci_execute($stmt);
while(($row = oci_fetch_array($stmt, OCI_BOTH)))
{
$ITEM_NAME = ($row["ITEM_NAME"]);
$SITE_CODE = ($row["SITE_CODE"]);
if(($ITEM_NAME === $sku) && ($SITE_CODE === $code))
{
$query_ora_update = "UPDATE app.ITEM_INFO SET ITEM_FLAG= 'Y', LAST_UPDATE_DATE = sysdate WHERE ITEM_NAME = '$sku' AND SITE_CODE = '$code' AND ITEM_FLAG = 'N' ";
$parse_result = oci_parse($conn,$query_ora_update);
$result = oci_execute($parse_result);
oci_commit($conn);
oci_close($conn);
}
}
plz guide me...
Basically, you just have to remove the while loop.
Here's a rewrite of your code applying that change (+ you use too many parenthesis, decreasing your code readability + you should use SQL binding to avoid injection):
$query_ora_update = "UPDATE app.ITEM_INFO SET ITEM_FLAG= 'Y', LAST_UPDATE_DATE = sysdate WHERE ITEM_FLAG = 'N'";
$parse_result = oci_parse($conn, $query_ora_update);
$result = oci_execute($parse_result);
oci_commit($conn);
oci_close($conn);
To fetch a single row in Oracle, add in your where clause the following condition:
ROWNUM = 1
Unfortunately could not understand the rest of your code, did not understand why the "ifs" if you already have the same condition in the where clause of your update.
The Oracle equivalent to mysql_fetch_assoc is oci_fetch_assoc :)
$parsed = ociparse($conn, $sql);
while ($row = oci_fetch_assoc($parsed))
{
// your logic here
}