I am trying to set an int value from an sql query. In my ios app I can assign an int value to a photo ID, store it and retrieve it fine. The problem comes if I want to overwrite the photo with a new jpg but still using the existing IdPhoto and therefore the same filename, e.g. 1.jpg. I first check whether the user exists. If so I update the photo (this is where I need to set the IdPhoto) otherwise I create a photo with a new ID (works fine).
function uploadDetails($Name, $Location, $photoData, $IdPhoto) {
$uploads = query("SELECT Name, IdPhoto FROM users WHERE Name = '%s' limit 1",$Name);
if (count($uploads['result'])>0) {
$result = query("UPDATE users SET Name='$Name', Location='$Location', IdPhoto='$IdPhoto' WHERE Name = '%s'", $Name);
//Need to define IdPhoto from users table
if (move_uploaded_file($photoData['tmp_name'], "icons/".$IdPhoto.".jpg")) {
thumb("icons/".$IdPhoto.".jpg", 180);
//I can print out confirmation to the iPhone app
print json_encode(array('$IdPhoto'=>$IdPhoto));
} else {
//print out an error message to the iPhone app
errorJson('Upload on server problem');
};
}
else {
if ($photoData['error']==0) {
$result = query("INSERT INTO users(Name, Location) VALUES('%s','%s')", $Name, $Location);
if (!$result['error']) {
// fetch the active connection to the database (it's initialized automatically in lib.php)
global $link;
// get the last automatically generated ID in the table
$IdPhoto = mysqli_insert_id($link);
if (move_uploaded_file($photoData['tmp_name'], "icons/".$IdPhoto.".jpg")) {
thumb("icons/".$IdPhoto.".jpg", 180);
print json_encode(array('successful'=>1));
} else {
errorJson('Upload on server problem');
};
} else {
errorJson('Upload database problem.'.$result['error']);
}
}
}
}
So the problem lies in the first part of the code where I need to update the photo but still use the same IdPhoto
EDIT
The piece of code I needed was as follows:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT IdPhoto FROM users WHERE Name = '$Name'"));
$IdPhoto = $getID['IdPhoto'];
Although I got to the answer eventually myself, I appreciate feedback of how to phrase questions better in future. And writing out the full code probably helped me look at the bigger picture and see where I was going wrong.
Your question is extremely vague but I'm going to take the following assumptions:
Your query will only ever return a single record
You are using MySQLi
Once you have run the query and stored the results into $result you can use the following code to get the IdPhoto:
//Store a row from results into variable
$row = $result->fetch_assoc();
//Store IdPhoto into variable
$IdPhoto = $row['IdPhoto'];
Note: Also you are selecting Name from the database when you already have the Name since you're using it to fetch the record
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 6 years ago.
I am attempting to implement a click count system. I am using the following code in this link Click here to see code, but changing it to modern standards. Initially I received errors for the msqli_real_escape_ string, but I believed I resolved it(no errors). Now, I am not receiving any errors at all, but the query is not sending into my database. I am using ini_set('display_errors', 1);
error_reporting(E_ALL); for error checking. Also I have my $con and session in and ini file that I call, so the session and connection are not issues.
Does anyone see what I am doing wrong or is there a good way I can check to see what isn't working?
//create current page constant
$curPage = mysqli_real_escape_string($con,htmlspecialchars($_SERVER['PHP_SELF']));
//set number of clicks variable to 0
$clicks = 0;
//do not recount if page currently loaded
if($_SESSION['page'] != $curPage) {
//set current page as session variable
$_SESSION['page'] = $curPage;
$click_sql = "
SELECT *
FROM click_count
WHERE page_url = ?
";
if (!$click_stmt = $con->prepare($click_sql)) {
$click_stmt->bind_param("s", $curPage);
$click_stmt->execute();
$num_rows = $click_stmt->fetchColumn();
if (!$click_stmt->errno) {
// Handle error here
}
$stmt->bind_result($click_id, $page_url, $page_count);
} elseif ($num_rows == 0) {
//try to create new record and set count for new page to 1
//output error message if problem encountered
$click_insert_stmt = "
INSERT INTO click_count
(page_url, page_count)
VALUES(?, ?)";
if(!$click_stmt = $con->prepare($click_insert_stmt)) {
$click_insert_stmt->execute(array('$curPage',1));
echo "Could not create new click counter.";
}
else {
$clicks= 1;
}
} else {
//get number of clicks for page and add 1 fetch(PDO::FETCH_BOTH)
while($click_row = $click_insert_stmt->fetch(PDO::FETCH_BOTH)) {
$clicks = $row['page_count'] + 1;
//update click count in database;
//report error if not updated
$click_update_stmt = "
UPDATE click_count
SET page_count = ?
WHERE page_url = ?
";
if(!$click_stmt = $con->prepare("$click_update_stmt")) {
$click_update_stmt->execute(array('$clicks', '$curPage'));
echo "Could not save new click count for this page.";
}
}
}
}
Edit: New Updated Code
// ********Page count************
//create current page constant
$curPage = mysqli_real_escape_string($con,($_SERVER['PHP_SELF']));
//set number of clicks variable to 0
$clicks = 0;
//do not recount if page currently loaded
if($_SESSION['page'] != $curPage) {
//set current page as session variable
$_SESSION['page'] = $curPage;
$click_sql = "
SELECT *
FROM click_count
WHERE page_url = ?
";
if (!$click_stmt = $con->prepare($click_sql)) {
$click_stmt->bind_param("s", $_SERVER['PHP_SELF']);
$click_stmt->execute();
$num_rows = $click_stmt->fetchColumn();
if (!$click_stmt->errno) {
// Handle error here
}
$stmt->bind_result($click_id, $page_url, $page_count);
} elseif ($num_rows == 0) {
//try to create new record and set count for new page to 1
//output error message if problem encountered
$click_insert_stmt = "
INSERT INTO click_count
(page_url, page_count)
VALUES(?, ?)";
if(!$click_stmt = $con->prepare($click_insert_stmt)) {
$click_insert_stmt->execute(array($curPage,1));
echo "Could not create new click counter.";
}
else {
$clicks= 1;
}
} else {
//get number of clicks for page and add 1 fetch(PDO::FETCH_BOTH)
while($click_row = $click_insert_stmt->fetch(PDO::FETCH_BOTH)) {
$clicks = $row['page_count'] + 1;
//update click count in database;
//report error if not updated
$click_update_stmt = "
UPDATE click_count
SET page_count=page_count+1
WHERE page_url = ?
";
if(!$click_stmt = $con->prepare("$click_update_stmt")) {
$click_update_stmt->execute(array($curPage));
echo "Could not save new click count for this page.";
}
}
}
}
It looks like you're doing a lot of stuff like this:
$click_update_stmt->execute(array('$clicks', '$curPage'));
I'm not sure where you picked up this habit of quoting variables as strings, but you need to drop it. '$x' and $x are two hugely different things. In the first case it's literally '$x' and in the second case it's whatever the $x variable happens to represent.
Fix it like this:
$click_update_stmt->execute(array($clicks, $curPage));
Also since you're using prepared statements, which by the way is great, you do not need to and should not manually escape your values. Applying them to placeholders with bind_param is the safe way of doing it. Doing any other escaping mangles the data.
Just bind directly to the source:
$click_stmt->bind_param("s", $_SERVER['PHP_SELF']);
Don't arbitrarily run things like htmlspecialchars on input out of paranoia or because you're doing cargo-cult programming and you saw it done in a YouTube tutorial somewhere. That function is intended to be used to display values only, not store them. Data in your database should be as raw as possible.
There's a lot of problems with this code, and one of them that has me confused is why there's so much code. Remember SELECT * and then binding results to arbitrary variables is trouble, your schema might change and then your code is out of sync. Whenever possible fetch rows as an associative array if doing this, then all you have to worry about is renamed ore removed columns.
The biggest problem is this is subject to race conditions because it doesn't use an atomic increment. When writing counters, always do your updates as operations that are a single statement:
UPDATE click_count SET page_count=page_count+1 WHERE page_url=?
Your approach of reading the count, incrementing it, and then writing it back into the database means that you're inviting problems if another operation runs concurrently, something very likely on click-counter code.
I have an html form that has some disabled field depending of what kind of authorization the user have. When I press submit, the script should understand which form field are posted and which not, and then update only the related field in the database.
For example:
I can modify Birthday, Birth place and sex, but Name and Surname are disabled and so are not posted by the html form. Therefore have to be updated only Birthday, BirthPlace, Sex where id = $idperson. But if I have permission, I post Name and Surname too. And therefore I should update also these value.
Is there a fast way to do it with PDO? Or I have to create a long sequence of if/else?
Sorry for my bad english
The Best and easy way to do this,
First collect post data and check id is set
fetch all data from your table using id
loop your post data and check with collected details
if collected details value and post value changed update in collected details variable
update all your fields with new collected array
Check the below code for more understanding
function collect() {
if(isset($_POST['id'])) {
// validate id and get all details from table
$details = getDetails($_POST['id']);
foreach($_POST as $key=>$value) {
// loop your post data and check with collected details if value changed update in collected details
if(array_key_exists($key, $details)) {
$details[$key] = ($details[$key] != $_POST[$key]) ? $_POST[$Key] : $details[$key];
}
}
} else {
echo "id not found to update";
}
}
function getDetails($id) {
$query = "SELECT * FROM table_name WHERE id=:id";
$stmt = $conn->prepare($query);
$stmt->bindParam(':id', $id);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
function update($details) {
$query = "UPDATE table_name SET field_1=:field_1, field_2=:field_2, all_field=:all_field WHERE id=:id";
$stmt = $conn->prepare();
$stmt->bindParam(':field_1', $details['field_1']);
...
$stmt->bindParam(':id', $details[$id]);
return $stmt->execute();
}
Hope this code helps you, Happy coding.
This is my block of code for doing that. It works fine until it reaches the last if statement. I cannot get it to find the Graphics column using the Department_ID. I am trying to check if the user input is equal to a id within the table. Then check if that id requires graphic work done. To do that, I need to find out that for that specific project graphic is a 1 in the database.
if($graphics_id != Null)
{
$query = mysqli_query($connect,"SELECT * FROM Project_Overview WHERE Project_ID='".$graphics_id."'");
$row = mysqli_fetch_assoc($query);
//echo $row['Project_ID'];
if($graphics_id == $row['Project_ID']) //if the graphics_id matches a project_id in the table
{
$result = mysqli_query($connect, "SELECT Graphics FROM Department WHERE Department_ID ='".$graphics_id."'")
$row = mysqli_fetch_assoc($result);
if($result)
{
echo $row['Department_ID'];
} else {
echo "This Project does not require graphics!"
}
} else {
echo "Project_ID ".$graphics_id." does not exist!";
}
}
A few thoughts:
The second SELECT Statement selects the Graphics column, but later you are echoing $row['Department_ID']; which should be empty as the only key in $row would be Graphics
The last if-Statement is if($result). Don't you mean if($row)? If $result is false (and hence "This Project does not require graphics!" is printed out), this would indicate, that mysqli_query has failed, possibly because of an error in your second SQL statement.
And, as ThomasEllis said, a JOIN would be nicer and SELECT * is not wrong but returns (probably) more than you need.
Depending on where $graphics_id comes from (a user input?) you should consider escaping it for security reasons ($graphics_id_escaped = mysqli_real_escape_string($connect, $graphics_id); - just in case ;)
I am trying to delete a specific entry in my MYSQL Database.
Database: PhotoID, IDCount, UserID.
This is my code for deleting a photo depending on the ID.
function delete($IdPhoto) {
$result = query("DELETE from photos WHERE IdPhoto='%d'", $IdPhoto);
if (!$result['error']) {
// if no error occured, print out the JSON data of the
// fetched photo data
print json_encode($result);
} else {
//there was an error, print out to the iPhone app
errorJson('Photo stream is broken');
}
}
This is paired with an iOS Application that grabs the current photos ID at all times. When a button is pressed, the delete function in the API will trigger. This doesn't seem to work though.
The following query works (specific ID):
$result = query("DELETE from photos WHERE IdPhoto=10");
Any help would be appreciated. The goal is to delete the photo depending on the $IdPhoto we grab in the iOS Application.
Try this:
$result = query("DELETE from photos WHERE IdPhoto={$IdPhoto}");
did you tried this :
$result = mysql_query("DELETE from photos WHERE IdPhoto='$IdPhoto' ");
you should use mysql_query
This
..IdPhoto='%d'
should be
..IdPhoto=%d
Since a int value shouldn't be surrounded by quotes
The "=" will only compare two int values or double values. Make sure you are comparing the type int. Thus your delete function should pass an int, otherwise you might need a function like getIntvalue() to extract the int value.
I get Nearest 50 km location names from current location using google api, so it' works fine.
So I need to insert all these locations into my database. If some location already there in database, I need to update these location.
For example I get 10 locations in google api so 5 locations are already there in my database. I need to 5 location are update and remaining 5 locations are insert.
Here is my code:
<?php
require 'dbconnect.php';
$LocaName=$_REQUEST['locname'];
$address=$_REQUEST['address'];
$latt=$_REQUEST['Latt'];
$long=$_REQUEST['Long'];
if($latt && $long)
{
$LocaNamearray = explode("|||", $LocaName);
$addressarray = explode("|||", $address);
$lattarray=explode("|||",$latt);
$longarray=explode("|||",$long);
for($i=0;$i<count($lattarray);$i++)
{
$query1="select * from tbl_MapDetails where Latitude='".$lattarray[$i]."'and Longitude='".$longarray[$i]."'";
$result1=mysql_query($query1);
$now=mysql_num_rows($result1);
}
if($now >=1)
{
for($k=0;$k<count($lattarray);$k++)
{
$query="update tbl_MapDetails set LocationName='".$LocaNamearray[$k]."', Address='".$addressarray[$k]."',Latitude='".$lattarray[$k]."', Longitude='".$longarray[$k]."' where Latitude='".$lattarray[$k]."'and Longitude='".$longarray[$k]."'";
}
$nav="update";
}
else
{
$query ="INSERT INTO tbl_MapDetails(LocationName,Address,Latitude,Longitude) VALUES";
$strDelimiter = "";
for($j=0;$j<count($LocaNamearray);$j++)
{
$name =$LocaNamearray[$j];
$address =$addressarray[$j];
$lat = $lattarray[$j];
$long = $longarray[$j];
$query .= $strDelimiter."('$name', '$address','$lat','$long')";
$strDelimiter = ',';
}
$nav="Add";
}
$result= mysql_query($query);
if($result)
{
echo mysql_error();
$message=array("message"=>"sucessfully".$nav);
}
else
{
echo mysql_error();
$message=array("message"=>"fail".$nav);
}
}
else
{
$message=array("message"=>"require latt and long");
}
echo json_encode($message);
?>
Here insert and update working but I need to check every location in database. There is no location in database. It need to insert other location are update. how to check both these conditions matched locations are update and unmatched locations are inserted Please guide me.
Your logic is wrong in the code. What you are doing is looping through the provided data and for each set of data checking if a location with that lat/long exists and storing it in the $now variable. Once you've finished that loop, you're then checking $now and looping through the provided data again and either INSERTing or UPDATEing each set of data. So if the last set of data exists, your script will try and UPDATE each set of data. If it doesn't, your script will try to INSERT each set of data. Your code should be something like this (mixture of your code and pseudo-code):
for($i=0;$i<count($lattarray);$i++)
{
$query1="select * from tbl_MapDetails where Latitude='".$lattarray[$i]."'and Longitude='".$longarray[$i]."'";
$result1=mysql_query($query1);
$now=mysql_num_rows($result1);
if($now >=1)
{
// update table with location details
}
else
{
// insert location details into table
}
}
If this becomes a performance issue you could look at retrieving all the SELECT data first but if you're only dealing with 10 rows at a time you should be OK.
Note: depending on where your $_REQUEST data is coming from you might want to do some validation, i.e. to check you have matching sets of lat/long/name/address details.
Take a look at MySQL`s ON DUPLICATE KEY UPDATE. But you must be careful, because it is quite slow operation.
But, I think, it would be better if you just union all your SELECT requests in one using OR conditions.