Saving items by multiple users in database - php

What am doing wrong ?
this might be the simple solution to all experts here, but i have tried all the ways and i dont know where is my mistake ?
The idea is to add and items through my page to my database and then i can check them as todo list or to buy list. As well is in future this will be toBuy/toDo list web application so whole family members add items and in the end of the day one refresh the page and get the whole items in the database fetched!
my codes are below:
TodoTobuy.php
<?php
include("includes/header.php");
include("./forms/fadd-items.php")
?>
<?php
try {
//Tiedot kantaan
/* var_dump($_POST); */
$data1['items'] = $_POST['givenItems'];
$data1['amount'] = $_POST['givenAmount'];
$STH = $DBH->prepare("INSERT INTO todoORtobuy (items, amount, id) VALUES (:items, :amount, :id);");
$STH->execute($data1);
$data4['id'] = $data1['id'];
$sql4 = "SELECT id FROM todoORtobuy where id =:id ORDER BY start DESC LIMIT 50";
$kysely4 = $DBH->prepare($sql4);
$kysely4->execute($data4);
$tulos2 = $kysely4->fetch();
$_SESSION["startDate"] = $tulos2[0];
} catch (PDOException $e) {
echo "Yhteysvirhe: " . $e->getMessage();
file_put_contents('log/DBErrors.txt', 'Connection: ' . $e->getMessage() . "\n", FILE_APPEND);
}
?>
My form
<fieldset>
<form method="post">
<p>
Items toDo \ toBuy:
<br /> <input type="text" name="givenItems" placeholder="Write what toDO\toBuy..." maxlength="100"/>
</p><p>
Amount needed:
<br /> <input type="text" name="givenAmount" placeholder="Write amount of what to buy..." maxlength="100"/>
</p>
<br /> <div>
<input type="submit" name="submitUser" value="Add" id="send" class="sendbutton"/>
</div>
</p>
</form>
</fieldset>
error i get is: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
I mean i kindda understand the error, but cant find the mistake! Thank you for helping in advance

$data1['items'] = $_POST['givenItems'];
$data1['amount'] = $_POST['givenAmount'];
$STH = $DBH->prepare("INSERT INTO todoORtobuy (items, amount) VALUES (:items, :amount);");
$STH->execute($data1);
In your code you are using 3 prepared values for your query but you only pass 2.
Also when inserting you don't need to insert the id, it should be set as auto-increment in your table and basically takes care of itself for each record you insert.

That how it worked i commented those in lower part, whichwas not needed.
thank you #pr1nc3
<?php
try {
//Tiedot kantaan
/* var_dump($_POST); */
$data1['items'] = $_POST['givenItems'];
$data1['amount'] = $_POST['givenAmount'];
$STH = $DBH->prepare("INSERT INTO todoORtobuy (items, amount) VALUES (:items, :amount);");
$STH->execute($data1);
/* $data1['id'] = $data1['id'];
$sql4 = "SELECT id FROM todoORtobuy where id =:id ORDER BY start DESC LIMIT 50"; */
/* $kysely4 = $DBH->prepare($sql4);
$kysely4->execute($data1);
$tulos2 = $kysely4->fetch();
*/
} catch (PDOException $e) {
echo "Yhteysvirhe: " . $e->getMessage();
file_put_contents('log/DBErrors.txt', 'Connection: ' . $e->getMessage() . "\n", FILE_APPEND);
}
?>

Related

How to insert data from a PHP form into a MySQL db with Foreign keys?

I am dealing with a PHP form containing checkboxes and a MySQL db. I finally achieved to insert multiple rows, one for each selected item, by looping over the array.
But now, I have to face another issue: in my DB, I have one principal table to store the one-choice questions and another table to store the answers from the checkboxes.
I would like to first execute the query inserting the one-choice answers into the principal table (one row per form), so that it generates a serial ID.
And secondly, to get back this ID and associate it to every row inserted into the checkbox table in order to link the two tables though this ID.
Is that possible please and how should I do?
Here the HTML code:
<input type="checkbox" name="nature_contact[]" value="1"><label >Phone</label><br/>
<input type="checkbox" name="nature_contact[]" value="2"><label >Mail</label><br/>
<input type="checkbox" name="nature_contact[]" value="3"><label >Visit</label><br/>
<input type="checkbox" name="nature_contact[]" value="4"><label >Unk</label> <br/><br/>
<input type="text" name="coord"/>
<br/>
<input type="text" name="tel"/>
<br/><br/>
<input type="submit" name="add" value="SEND"/>
And here the PHP part:
try {
if(isset($_POST['add'])){
if(isset($_POST['coord'])) {
$coord=$_POST['coord'];
}
else { $coord = '';
}
if(isset($_POST['tel'])) {
$tel=$_POST['tel'];
}
else { $tel = '';
}
$query="INSERT INTO nmp_mfs.general (coord, tel) VALUES ('".$coord."', '".$tel."')";
$statement_gnl = $pdo->prepare($query);
$statement_gnl->execute();
}
}
catch(PDOException $e) {
$msg = 'ERREUR PDO dans ' . $e->getFile() . ' L.' . $e->getLine() . ' : ' . $e->getMessage();
die($msg);
}
try {
if(isset($_POST['add'])){
if(isset($_POST['nature_contact'])) {
$sql = "INSERT INTO nmp_mfs.t_temporaire (nature_contact) VALUES ".rtrim(str_repeat('(?),', count($_POST["nature_contact"])), ',');
$statement = $pdo->prepare($sql);
$count = 1;
foreach($_POST["nature_contact"] as $nature_contact) {
$statement->bindValue($count++, $nature_contact);
}
$statement->execute();
}
}
}
catch(PDOException $e) {
$msg = 'ERREUR PDO dans ' . $e->getFile() . ' L.' . $e->getLine() . ' : ' . $e->getMessage();
die($msg);
}
Yes this is possible.
You need the last inserted id of the principal table row like:
$lastInsertedID = $db->lastInsertId();
1.) Insert the question in the database table (principal)
2.) Get the last inserted id ($lastInsertedID)
3.) Insert answers related to the question in the answer table and provide the last inserted id.
$query = "INSERT INTO nmp_mfs.t_temporaire (questionID, nature_contact)
VALUES ($lastInsertedID, $nature_contact)"; // Example
4.) Select the ID's of your questions.
5.) Get the corresponding answers:
$query = "SELECT awnsers WHERE question_id = questionID"; // Simple example
To make sure your data synchronized,you can use transaction in mysql.Sorry for my poor english, I just want to do something useful.

Left join and last inserted ID dilemma

hi in want to build a registration and lottery app with php
i want to make a users id in my prize table upon registration of users and i want to add to a number of my buy_count when users buy a ticket...
so i got 2 tables :
prize , users
prize : users_id , buy_count
users : fn , ln , pass...usual staff
this is the sctipt for users reg form :
$sql = 'INSERT INTO users (id,fn,ls,psw) VALUES (:id,:fn,:ln,:psw);
INSERT INTO prize (user_id, buy_count) VALUES (LAST_INSERT_ID(), 4)';
script gives me an error , whats wrong with it ? i want to add to users id in prize table upon user registration , whats the problem with my query ?
whats the right way to do this ?
UPDATED :
so now this is my code :
<?php
try {
require_once 'inc/connect.php';
$sql =("
INSERT INTO users (fn,ls,psw) VALUES (:fn,:ln,:psw);
INSERT INTO prize (user_id) VALUES (LAST_INSERT_ID());
");
$form = $_POST;
$fn = $form['fn'];
$ln = $form['ln'];
$psw = $form['psw'];
$values = array(
':fn' => $fn ,
':ln' => $ln ,
':psw' => $psw
);
$stmt = $db->prepare($sql);
$stmt->execute($values);
if ( $stmt ){
echo "<p>Thank you. You have been registered</p>";
} else {
echo "<p>Sorry, there has been a problem inserting your details. Please contact admin.</p>";
}
$errorInfo = $db->errorInfo();
if (isset($errorInfo[2])){
$error = $errorInfo[2];
}
} catch (Exception $e) {
$error = $e->getMessage();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Database Connection with PDO</title>
<link href="../../styles/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Connecting with PDO</h1>
<?php if(isset($error)) {
echo "<p>$error</p>";
}else {
?>
<?php
if ( empty( $_POST ) ) {
?>
<h1>Registration</h1>
<form name="" action="" method="POST">
<label for 'username'>Username: </label>
<input type="text" name="fn"/>
<label for 'password'>Password: </label>
<input type="password" name="psw"/>
<label for 'first_name'>First name: </label>
<input type="text" name="fn"/>
<br/>
<button type="submit">Submit</button>
</form>
<?php
} else {
print_r( $_POST );
}
?>
<?php } //error ?>
</body>
</html>
still doesnt do what i want ... doesnt add any data to the tables and AI users_id with last I I
anyone can help with this ?
Short answer: RTM
Long answer (from the mysql documentation) When a new AUTO_INCREMENT value has been generated, you can also obtain it by executing a SELECT LAST_INSERT_ID() statement
You are not generating a new ID automatically, you are specifying the value directly. So you can do one of two things, remove the id column and value :id placeholder from your first query OR use the same :id placeholder in your second query.

PHP SQL query server error

I have a table as so:
TABLE click_count
(
count int(3)
);
which is currently an arbitrary number. I have this php script with an html button which should just increment the number by one. The SQL query works in php my admin but gets an error when it's ran on the page.
<?php
require("config.inc.php");
if(!empty($_POST)){
$query = "UPDATE click_count
SET count = count + :submit_1
";
$query_params_ = array(
'submit_1' => $_POST['count']
);
try {
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["message"] = "Database Error. Please Try Again!";
die(json_encode($response));
}
$response["message"] = "Vote Cast!";
echo json_encode($response);
} else {
?>
<form action="vote.php" method="post">
Count:<br />
<input type="number" name="submit_1" value="1" />
<br /><br />
<input type="submit" value="Cast Vote" />
</form>
<?php
}
?>
You have to change your array key to match the one in preparedStatement. Like this:
$query_params_ = array(':submit_1' => $_POST['count']);
Indeed, you are refering to $query_params in the execute() method, but you are defining $query_params_ (with underscore in the end).
count is a reserved keyword of mysql, see: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
try to enclose it into accents, like this:
UPDATE click_count
SET `count` = `count` + :submit_1
";

Insert comment to database with the right ID to match and ad (php , mysql)

Im trying to make so that you can comment on an ad, on a buy/sell site.
On the main page im showing all the ads (all ad’s have an id named AdID) and under every ad i have a comment section.
My problem is that I cant seem to pass my AdID from the right ad to the if statement where I make my INSERT statement.
I could solve it by having the comment section on a different page and pass the AdID with $_GET but I really want people to be able to comment under the ad on the main page.
Help would be appreciated and if you need the rest of the code please say so.
$res2 = $mysqli->query($query) or die("Could not query database" . $mysqli->errno . " : " . $mysqli->error); //Performs query
while($row2 = $res2->fetch_object()) {
$Comment = utf8_decode(htmlspecialchars($row2->Comment));
$AdID = utf8_decode(htmlspecialchars($row2->AdID));
$UserID = utf8_decode(htmlspecialchars($row2->UserID));
$Fname1 = utf8_decode(htmlspecialchars($row2->Fname));
$Lname1 = utf8_decode(htmlspecialchars($row2->Lname));
$c .= <<<END
<div class="CommentBox">
{$Fname1} {$Lname1}
{$Comment}
</div>
END;
}
if(!empty($_POST)) {
$msg = utf8_encode($mysqli->real_escape_string($msg));
$UserID = isset($_SESSION["UserID"]) ? $_SESSION["UserID"] : "NULL";
$query = <<<END
INSERT INTO comment (Comment, UserID, AdID)
VALUES('{$msg}', '{$UserID}' , '{$AdID}' );
END;
$res = $mysqli->query($query) or die("Could not query database" . $mysqli- >errno . " : " . $mysqli->error); //Performs query
}
$c .= <<<END
<form action="comTest.php" method="post">
<input type="text" id="stor" name="msg" value="{$msg}" placeholder="Comment"/>
</form>
END;
}
You didn't get msg value posted from form. You need to get it first;
$msg = $_POST["msg"];
And also, put a hidden element to form so, you can get ad ID like;
<form action="comTest.php" method="post">
<input type="text" id="stor" name="msg" value="{$msg}" placeholder="Comment"/>
<input type="hidden" id="adId" name="adId" value="$AdID"/>
</form>

POST method and arrays

This is my first php project. I have created a website where users can upload their picture and then view the pictures of other users, one person at a time (similar to the old hotornot.com). The code below works as follows:
I create an array (called $allusers) containing all members except for the user who is currently logged in ($user).
I create an array (called $usersiviewed) of all members who $user has previously either liked (stored in the likeprofile table) or disliked (stored in the dislikeprofile table). The first column of likeprofile and dislikeprofile has the name of users who did the liking/disliking, second column contains the name of the member they liked/disliked.
I use the array_diff to strip out $usersiviewed from $allusers. This is the list of users who $user can view (ie, people they have not already liked or disliked in the past).
Now the problem is when I click the like button, it updates the likeprofile table with the name of the NEXT person in the array (i.e., not the person who's picture I am currently looking at but person who's picture appears next). Additionally, if I refresh the current page, the person who's profile appears on the current page automatically gets 'liked' by me. I would really appreciate any advice on this.
<?php
// viewprofiles.php
include_once("header.php");
echo $user.' is currently logged in<br><br>';
echo <<<_END
<form method="post" action="viewprofiles.php"><pre>
<input type="submit" name ="choice" value="LIKE" />
<input type="submit" name ="choice" value="NEXT PROFILE" />
</pre></form>
_END;
$allusers = array();
//Create the $allusers array, comprised of all users except me
$result = queryMysql("SELECT * FROM members");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;
$allusers[$j] = $row[0];
}
//Create the $i_like_these_users array, comprised of all users i liked
$result = queryMysql("SELECT * FROM likeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_like_these_users[$j] = $row[1];
}
//Create the $i_dislike_these_users array, comprised of all users i disliked
$result = queryMysql("SELECT * FROM dislikeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_dislike_these_users[$j] = $row[1];
}
//Create the $usersiviewed array, comprised of all users i have either liked or disliked
if (is_array($i_like_these_users) && is_array($i_dislike_these_users))
{
$usersiviewed = array_merge($i_like_these_users,$i_dislike_these_users);
}
elseif(is_array($i_like_these_users))
{
$usersiviewed = $i_like_these_users;
}
else
{
$usersiviewed = $i_dislike_these_users;
}
// this removes from the array $allusers (i.e., profiles i can view) all $usersviewed (i.e., all the profiles i have already either liked/disliked)
if (is_array($usersiviewed))
{
$peopleicanview = array_diff($allusers, $usersiviewed);
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
else {
$peopleicanview = $allusers;
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
$current_user_profile = $peopleicanview[0];
echo 'check out '.$current_user_profile.'s picture <br />';
if (file_exists("$current_user_profile.jpg"))
{echo "<img src='$current_user_profile.jpg' align='left' />";}
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['choice']) && $_POST['choice'] == 'LIKE')
{
$ilike = $current_user_profile;
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$ilike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['choice']) && $_POST['choice'] == 'NEXT PROFILE')
{
$idontlike = $current_user_profile;
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$idontlike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
?>
Because when you refresh page it sends previus value of
Form again...and problem when u like a user it being liked next user.. There there is something in yor for loop while fetching row ...insted of for loop try once while loop ...i hope it will solve ur problem
You are calculating the $iLike variable with the currently loaded user and then updating the database with that user.
You should probably change your application logic a bit:
pass the user ID of the user you liked or did not like as a POST parameter in addition to the like/didn't like variable
move the form processing logic to the top of your page (or better yet separate out your form processing from HTML display)
Also, it's best not to use the mysql_* extensions in PHP. Use mysqli or PDO.
Try to make two different forms. One with "LIKE", another with "NEXT" to avoid liking from the same form
When you submit your form - your page refreshes, so in string $current_user_profile = $peopleicanview[0]; array $peopleicanview doesn't have user from previuos page (before submitting) you have to attach it, e.g. in hidden field
<form method="post" action="viewprofiles.php">
<input type="hidden" name="current_user" value="$current_user_profile" />
<input type="submit" name ="choice" value="like" />
</form>
<form method="post" action="viewprofiles.php">
<input type="submit" name ="go" value="next" />
</form>
and INSERT it later
"INSERT INTO likeprofile VALUES" . "('$user', '".$_POST['current_user']."')"
ps remove <pre> from your form
Lets start by simplifying and organizing the code.
<?php
// viewprofiles.php
include_once("header.php");
//if form is sent, process the vote.
//Do this first so that the user voted on wont be in results later(view same user again)
//use the user from hidden form field, see below
$userToVoteOn = isset($_POST['user-to-vote-on']) ? $_POST['user-to-vote-on'] : '';
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['like']))
{
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['dislike']))
{
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
//now we can create array of available users.
$currentProfileUser = array();
//Create the $currentProfileUser array,contains data for next user.
//join the 2 other tables here to save php processing later.
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
and `user` <> '$user'
LIMIT 1");
//no need for a counter or loop, you only need the first result.
if(mysql_num_rows > 0)
{
$row = mysql_fetch_assoc($result);
$current_user_profile = $row['user'];
}
else
$current_user_profile = false;
echo $user.' is currently logged in<br><br>';
//make sure you have a user
if($current_user_profile !== false): ?>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="like" value="LIKE" />
</form>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="dislike" value="NEXT PROFILE" />
</form>
check out <?=$current_user_profile?>'s picture <br />
<?php if (file_exists("$current_user_profile.jpg")): ?>
<img src='<?=$current_user_profile.jpg?>' align='left' />
<?php endif; //end check if image exists ?>
<?php else: //no users found ?>
Sorry, there are no new users to view
<?php endif; //end check if users exists. ?>
You'll notice I changed the code a lot. The order you were checking the vote was the main reason for the issue. But over complicating the code makes it very difficult to see what's happening and why. Make an effort to organize your code in the order you expect them to run rather a vote is cast or not, I also made an effort to separate the markup from the logic. This makes for less of a mess of code to dig through when looking for the bug.
I also used sub queries in the original query to avoid a bunch of unnecessary php code. You could easily have used JOIN with the same outcome, but I think this is a clearer representation of what's happening. Also please use mysqli instead of the deprecaded mysql in the future, and be aware of SQL injection attacks and makes use of real_escape_string at the very least.
Hope it works out for you. Also I didn't test this code. Might be a few errors.

Categories