Php code to update or insert values - php

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

Related

Duplicate entry '1' for key 'PRIMARY' when updating the table

I have a problem when trying to update table after checking row. Not sure if the "if" statement is wrong, however I'm not quite sure, why the UPDATE sql is returning this error. I wouldn't be suprised if INSERT did that.
Here's part of code:
$sql = "SELECT user_id FROM players WHERE user_id = '$id'";
$result = $connect->query($sql);
if($result->num_rows > 0)
{
$sql = "UPDATE players SET user_id = '$Player->user_id', display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
if($connect->query($sql) === TRUE)
{
echo 'Table has been successfully updated.';
}else{
echo 'There has been a problem with updating the "players" table. <br>Error: '.$connect->error;
}
}else{
$sql = "INSERT INTO players(user_id, display_name, attackPower, defensePower) VALUES('$Player->user_id', '$Player->display_name', '$Player->attackPower', '$Player->defensePower')";
if($connect->query($sql) === TRUE)
{
echo'Table has been successfully migrated.';
}else{
echo'Table migration has failed.';
}
}
$connect->close();
INSERTing is working just fine. I would appreciate any advice. Thanks.
Your update query should look like:
$sql = "UPDATE `players` SET `display_name` = '{$Player->display_name}',
`attackPower` = '{$Player->attackPower}', `defensePower` = '{$Player->defensePower'}
WHERE `user_id` = '{$Player->user_id}'";
It cause an error because Identity columns are not updateable.
You can update every columns except them:
$sql = "UPDATE players SET display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
As #aynber and #Julqas said, problem was my sql was missing WHERE condition. Thanks for help.

mySql query does not find the row

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."");

Query does not work when i fetch data and insert it into a table

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.

Can't update then insert in SQL

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.

Converting from mysql to mysqli (mysql_fetch_array) [duplicate]

This question already has answers here:
How to change mysql to mysqli?
(12 answers)
Closed 1 year ago.
I have some php code that was like this:
$row = mysql_fetch_array ( mysql_query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'"));
I'm now trying to convert it to mysqli_fetch_array as shown here http://php.net/manual/en/mysqli-result.fetch-array.php (Example #1 Object oriented style)
I'm not sure what the example means by "$result".
This is what I've converted my code to so far:
<?php
include('../config.php');
if (isset($_GET['uid']) ) {
$uid = $_GET['uid'];
$id = $_GET['id'];
if (isset($_POST['submitted'])) {
foreach($_POST AS $key => $value) { $_POST[$key] = mysqli_real_escape_string($value); }
//Query for tblFacilityHrs
$sql = " UPDATE tblFacilityHrs SET `title`='{$_POST['title']}',`description`='{$_POST['description']}' WHERE `uid` = '$uid' ";
$result = $mysqli->query($sql) or die($mysqli->error);
//Query for tblFacilityHrsDateTimes
$sql2 = "UPDATE tblFacilityHrsDateTimes SET `startEventDate`='{$_POST['startEventDate']}',`endEventDate`='{$_POST['endEventDate']}', `startTime`='{$_POST['startTime']}',`endTime`='{$_POST['endTime']}',`days`='{$_POST['days']}',`recurrence`='{$_POST['recurrence']},`finalDate`='{$_POST['finalDate']}' WHERE `id` = '$id' "; print $sql2;
$result2 = $mysqli->query($sql2) or die($mysqli->error);
echo ($mysqli->affected_rows) ? "Edited row.<br />" : "Nothing changed. <br />";
echo "<a href='list.php'>Back</a>";
}
$row = $result->fetch_array($mysqli->query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'"));
$row2 = $result2->fetch_array($mysqli->query("SELECT * FROM `tblFacilityHrsDateTimes` WHERE `id` = '$id'"));
?>
There is probably a lot wrong with as I am learning mysqli, but right now it errors on
Fatal error: Call to a member function fetch_array()
UPDATE queries do not return result objects, it returns TRUE (assuming success). You're then trying to call TRUE->fetch_array(), which obviously won't work.
Now, for doing what you actually want to do, try this:
$row = $mysqli->query("SELECT.....")->fetch_array();
Looks like you are trying to use an old result object (result of your UPDATE) to get results for a new query. You need to run the new query first, assign its result to an object, and then fetch the results from object. Check out the last three lines of your script re-written:
$facilityHoursQueryResult = $mysqli->query("SELECT * FROM `tblFacilityHrs` WHERE `uid` = '$uid'");
$facilityHoursDateTimesQueryResult = $mysqli->query("SELECT * FROM `tblFacilityHrsDateTimes` WHERE `id` = '$id'");
$facilityHoursRow = $facilityHoursQueryResult == FALSE ? NULL : $facilityHoursQueryResult->fetch_array();
$facilityDateTimesRow = $facilityHoursDateTimesQueryResult == FALSE ? NULL : $facilityHoursDateTimesQueryResult->fetch_array();
?>
Here is a helpful page with other result object methods:
http://www.php.net/manual/en/class.mysqli-result.php

Categories