Hello I am new into PHP and Mysql - well I am developing an android app that will retrieve some user data from a server mysql db table - data like username, firstname, last name, addresse etc..and the user has the option to edit that all or some of them...and lastly click the update button to update the data back to the mysql database.
So the problem is - should I return all the values (edited and those that are not) with the POST['username'], POST['fname'], .... etc - and then update the database with data that are changed and not changed - or should I RETURN ONLY THE EDITED DATA and then somehow update these fields in the table (BUT i am not sure how to implement this - to make a SWITCH statement with cases for every type of POST['fname'] and there update every single column with the POST value)
OR DO YOU KNOW SOME BETTER LOGIC/PATTERN FOR THIS - paste some links with examples/tuts if you know?
THANKS
This works in PHP, although prepared statements are better:
$sql = "
UPDATE userData
SET
";
if(isset($_POST['firstname'])
$sql .= "`firstname` = '" . $_POST['firstname'] . "'";
if(isset($_POST['lastname'])
$sql .= "`lastname` = '" . $_POST['lastname'] . "'";
// You get the picture
$sql .= "
WHERE userid = $id";
You should send a flag indicate the edited fields and depending on the flag write your update statement, for example if username and fname are changed, send a flag USERNAME_FNAME_CHANGED and then expected 2 fields username and fname being sent from your device. Then in the server implements a switch statement to write the update statement accordingly.
Related
I've created a route planner where users travel to work and gain points based on the type of transport they use, I want to then store the points they earn cumulatively in a database I have created, but I am having a problem with using the JavaScript variable from the Route Planner so that it is inserted into the database, as I do not know the right SQL statement to use.
I've changed the SQL statements from 'INSERT INTO' to 'UPDATE' by changing the field in the database host I use and taking it from that. However, I want points to be stored cumulatively, not overwrited.
I've changed the JavaScript on the page and the PHP works when a correct SQL statement is used.
<?php
include('Link.php');
$stmt = $mysqli->prepare("UPDATE `Employees` SET `carbo_points` = 400 WHERE
`Employees`.`employee_id` = 1; ");
$stmt->bind_param('i', $_POST['CarboPoints']);
$stmt->execute();
$stmt->close();
echo "Carbo Points have been stored.";
?>
This will change the Carbo Points of the user with employee id 1 to 400 in the database. However, I want a working SQL statement where the user adds the 'CarboPoints' they earned from that specific journey to their current total. But I do not know how to include the 'CarboPoints' variable I have created in ajax within the SQL statement.
It seems do you have several questions:
1.- Add instead overwrite You can change sql to add points: SET carbo_points = carbo_points + new_points.
2.- Get points from ajax parameters Just use ? to parametrize query: carbo_points = carbo_points + ? .
In summary:
$stmt = $mysqli->prepare("UPDATE `Employees`
SET `carbo_points` = `carbo_points` + ?
WHERE `Employees`.`employee_id` = 1; ");
$stmt->bind_param('i', $_POST['CarboPoints']);
$stmt->execute();
$stmt->close();
Hello Im writing a voting system for fun. The idea is that you vote on a music playlist, therefor the most popular song by vote gets played next. The track names as well as number of votes are stored in a mysql database. I am able to read data from my database and displaying the track names in a row with a button next to it. But I cant figure out how to make the button update the number of votes the track next to it has.
My database has a table called votecount with 3 columns called track_id track_name track_votes respectively. I havent included my update function below since it wont work at all and I suspect my fault lies with somewhere else.
I think of using the track id in a way of determining which track it should update by +1 each time the button next to it is pressed.
i have included connecting to the database in a separate file called connect.php
<?php
include 'connect.php';
$sql = <<<SQL
SELECT *
FROM `votecount`
SQL;
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
echo $row['track_name'] . " TotalVotes ( " . $row['track_votes'] . " ) <form action='test.php' method'post'>
<input name='" . $row['track_name'] . "' type='submit' id='" . $row['track_id'] . "'value='vote'></input>
<br/></form>";
}
?>
Any help will be greatly appreciated thanks in advance!
There are few ways to do it, the easiest would be a link, to your script where you pass in the track id a query string:
echo "vote";
Then inside of test.php retrieve the id $_GET['id'] then run the query to add a vote.
or you can use Ajax to perform a request to your script and pass in the track id.
New to learning PHP form validation on same page. Please advise as to why my data might not be posting to the database. After filling out the form, it redirects to thank you page without sending data. Thanks!
http://pastebin.com/3T1W9Krx
Edit: Now that I know where my problem was, I have updated the Pastebin file to show the working code, which validates in the same page and checks the database for duplicate email addresses.
I was able to use Rick Kuipers suggestion below to find this error. I was trying to include a column for the primary key under VALUES, however I only needed the values for the INSERT keys, not ID or timestamp, as ID is set to auto-increment.
$sql = "INSERT INTO table (last_name, first_name, age)
VALUES (".
PrepSQL($last_name) . ", " .
PrepSQL($first_name) . ", " .
PrepSQL($age) . ")";
mysql_query($sql);
header("Location: volthankyou.php");
exit();
}
}
This could be because of a problem with your query.
Try doing the following:
echo mysql_error($db);
//header("Location: volthankyou.php");
This should display the error if there is any.
Check if mysql_query is true or false for your insert. Otherwise, it will ALWAYS try and then, redirect to thankyou. And as spencercw points out, mysql_select_db could also be failing. Always check the result of such methods.
P.S.: always check server logs
I was wondering if you can maybe help me out here... I created a link sharing website and managed to create a comment on a shared link.
I want to give you a scenario of what I would like to achieve. Every comment made by user_1 for instance, can only be deleted by user_1 and admin.
I understand that when "deleting" it from the php page it must also be dropped from the database. How can you do this?
//I pressume where I INSERTED my post's 'vales' I must DELETE them again from there??
//It is very much alike from reply.php's code where you INSERT the data into the database. Now I just want to delete it.
//I don't know if this code below is correct??
$sql = "DELETE FROM
posts(post_content,
post_date,
post_topic,
post_by)
WHERE ('" . $_POST['reply-content'] . "',
NOW(),
" . mysql_real_escape_string($_GET['id']) . ",
" . $_SESSION['user_id'] . ")";
$result = mysql_query($sql);
if(!$result)
{
echo 'Your reply has not been saved, please try again later.';
}
else
{
echo 'Your comment has been deleted!';
}
Your Delete query has major syntax errors. You don't delete individual fields from a table - you CAN'T. you can only delete entire records. The proper syntax is:
DELETE FROM sometable WHERE (...)
Your where clause also has errors. You're not doing any comparison operations, just listing some values. Again, a syntax error. Most like you'd want this (guessing at your post's table primary key field name):
DELETE FROM posts WHERE (post_id = $id);
You should give your comments ID's, and simply perform delete from posts where ID = $id.
The SQL statement you currently have won't even execute. Look at the manual for how the syntax works.
What would really be helpful is some separation of presentation logic from db logic from bus. logic. Try a MVC pattern, which makes it a lot easier to parse through the code and to only look at DB or presentation or bus. logic code. Then, we could focus on the answer to the question posted.
I have to create a database for a class and I am having trouble with one thing. In the database, a user can search for other users and choose to friend them (just like facebook). In my php scripts, I am searching my 'user' table (in MySQL) for all users that match a string entered in by the logged-in user, and providing a list of names that match the string. The logged in user can then click on the name they would like to friend, and a request is sent to that person. I am not sure how to retrieve the username and id of the name that is clicked on. For example, if the list of names that are displayed is:
Sally
Kevin
Mike
and the user clicks on Sally, how can I retrieve her username and id? In the sql query I am using, the last person is at the top of the array, so they logged in user always tries to friend Mike. Any suggestions would be great!!
The $_SESSION values are taking the last name in the array. How can I get it to take the name the logged-in user clicks on?
Or is there a better way to do this?
Here is my code so far:
$sql="SELECT uid, name FROM user WHERE name LIKE '%" . $name . "%'";
//run the query against the mysql query function
$result=mysql_query($sql);
//create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$name=$row[name];
$uid=$row[uid];
//display the result of the array
echo "<ul>\n";
echo "" .$name. "";
echo "</ul>";
$_SESSION['friend_name'] = $name;
$_SESSION['friend_id'] = $uid;
}
I see you are generating the url with a name which in your case is not a key in the database. Why not send the UID itself to the friend_request.php and then use that UID to send the request to that person.
echo "" .$name. "";
Remove the $_SESSION variable, you dont need it.
In the friend_request.php, change $_SESSION['uid'] and $_SESSION['name'] to
$_GET['uid'] and $_GET['name']
You should pass the value of the friend being selected to the request that's selecting it, rather than trying to store it in session. Something like this:
echo "" .$name. "";
That way the value selected will be available to the friend_request.php script as $_GET['name'].
it depends on how you generate the persons list that user want to chose from so the list may be like :
sally
and in your php code aka makefriend.php you can get the user id and name from the db like :
$result = mysql_query("SELECT uid, name FROM user WHERE name LIKE '%" . $_get['name'] . "%'
i hope this can help .