Conditions:
1. Let's say, I have a table like this:
create table users (
id int not null auto_increment primary key,
first_name varchar(255),
last_name varchar(255),
email varchar(255)
);
And I have a simple form users/add with 2 input fields - user and email - and submit button
What I want to do is the following: I want to insert Form data based on what is typed inside user field. I mean if I type a word all, cakePHP will insert the same email for all users in that table. If I type only one digit (i.e. id), cakePHP will insert email only for a user with this id.
How do I do that?
here is some controller code that might help you out.
function add()
{
if ($this->request->data['inputName'] == 'all') {
$this->User->updateAll(
array('User.email' => value)
);
} else {
$this->User->id = $this->request->data['inputName'];
$this->User->saveField('email', value);
}
}
saveField
updateAll
Related
First off, forgive me the unsafe code, I will work on that later on.
For now this problem:
I have a page with a form to which a user can add fields and modify existing fields.
I sent the form and when the input is new I also create an empty hidden input field for the primary key column that's empty to add a new row to db. Only this row is not being created. When user modifies existing row it does work. So the update on duplicate key part works, but the Insert part for a new field does not work.
I already used print_r to check what the variables look like and indeed like I wanted for a new field footNoteID is empty and footNoteNL contains whatever user entered, and for a modified field footNoteID has the old primary key value and whatever was modified. So that looks alright.
Yet the Insert part for a new field does not work.
This is the code on the php page that processes the form:
// two posted arrays from a form with multiple input fields
$footNoteNL = $_POST['footNoteNL'];
$footNoteID = $_POST['checkfootNoteID'];
// looping through the arrays
for($j=0, $count = count($footNoteNL); $j<$count; $j++) {
$footNoteNLThis = $footNoteNL[$j];
$footNoteIDThis = $footNoteID[$j];
$sql4 = "INSERT INTO footnotes (footNoteID, albumID, addedDate, footNoteNL, footNoteEN) VALUES ('".$footNoteIDThis."', '92', '".$datum."' , '".$footNoteNLThis."', 0)
ON DUPLICATE KEY UPDATE footNoteNL = '".$footNoteNLThis."'";
$result = mysqli_query($conn, $sql4);
This is the form on the HTML side, and the jquery that adds the input and hidden field. This part works. I use brackets on the form field to create a posted array. Like said, when checking what gets posted it seems ok.
$(document).ready(function () {
$('.addButton').on('click', function () {
$(".footNoteContainer").prepend("<div><input type='hidden' name='checkfootNoteID[]' value=''><TEXTAREA NAME='footNoteNL[]'></TEXTAREA>
// and so on
The part of the form this gets prepended to:
foreach ($mysqli->query('SELECT * FROM footnotes WHERE albumID = '.$album_id.' ORDER BY addedDate ASC') as $row ) {
<TEXTAREA NAME='footNoteNL[]'>".stripslashes($row['footNoteNL'])."</TEXTAREA>
<input type=\"hidden\" NAME=\"checkfootNoteID[]\" VALUE=\"".stripslashes($row['footNoteID'])."\">
// and so on, just to show that here the field are non empty since they get pulled form db
and here is what a check looks like when adding a new field, and modifying an existing ones: "_newly added field value 9092_old input value"
So before the underscore of the newly created field, there is no value for $footNoteIDThis , which makes me expect a new row gets added to db. For the modified field there is the old key "9292" so that\s a duplicate and indeed that one gets updated ...
this is dump form db:
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
--
-- Table structure for table `footnotes`
--
CREATE TABLE `footnotes` (
`footNoteID` int(111) NOT NULL,
`albumID` int(11) NOT NULL,
`addedDate` date NOT NULL,
`footNoteNL` text NOT NULL,
`footNoteEN` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- Indexes for table `footnotes`
--
ALTER TABLE `footnotes`
ADD PRIMARY KEY (`footNoteID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `footnotes`
--
Sorry for all the info, hopefully it makes sense, sorry for cumbersome method, but I really don't see why this doesn't work, although I suspect the problem lies in the db table settings or structure?
This question already has an answer here:
Mysql - Add auto_increment to primary key
(1 answer)
Closed 9 years ago.
I have a form that sends the data it captures in to a database, i have a primary key attached to my table (form_id) which i want to autoincrement everytime a new form is submitted and consequently added into my database table. Currently it is just adding a 0 for the first form submitted then anymore forms i submit after do not show as it gives me a message saying you can not have two rows with the same id as zero, which is correct so i would like to change this?
Below is my php code that submits the data into the database:
public function action_claimincentive() {
$this->template->content = View::factory('crm/uk/claim_incentive_form');
$this->template->content->thanks = false;
$this->template->content->val = '';
$this->template->content->post = '';
if ($this->request->post('form')) {
$post = $this->request->post('form');
$stmt = DB::query(Database::INSERT, 'INSERT INTO `claim_incentive_form_data` (`Claimant Name`, `Claimant Postcode`, `Purchase Order No.`, `Claimant Email Address`, `Storename`, `Storetown`, `Date of Sale`, `Date of Delivery`, `Tempur Acknowledgement No.`, `Tempur Product`)
VALUES (:claimantname, :claimantpostcode, :orderno, :email, :storename, :storetown, :dateofsale, :dateofdelivery, :acknowledgementno, :tempurproduct)');
$stmt->param(':claimantname', $post['claimantname']);
$stmt->param(':claimantpostcode', $post['claimantpostcode']);
$stmt->param(':orderno', $post['orderno']);
$stmt->param(':email', $post['email']);
$stmt->param(':storename', $post['storename']);
$stmt->param(':storetown', $post['storetown']);
$stmt->param(':dateofsale', $post['dateofsale']);
$stmt->param(':dateofdelivery', $post['dateofdelivery']);
$stmt->param(':acknowledgementno', $post['acknowledgementno']);
$stmt->param(':tempurproduct', $post['tempurproduct']);
try {
$stmt->execute();
$this->template->content->post = $post;
$this->template->content->thanks = true;
} catch (Exception $e) {
FB::error($e);
}
}
}
This sounds more like a MySQL issue rather than anything else. Make sure you have your Primary Key setup to auto increment. Try altering the table to add the auto increment feature:
ALTER TABLE [table name] MODIFY COLUMN [column name] [column type] PRIMARY KEY AUTO_INCREMENT;
In the above example. Replace the keys in brackets with their appropriate names. Replace [table name] with the name of your table, [column name] with the name of the column and [column type] with the type of the column (SMALLINT, INT, etc).
For more information, see this answer posted by roman.
For more information on the AUTO_INCREMENT feature, check out the MySQL Development Documentation here.
You need to add AUTO_INCREMENT to the primary key column on the table check this http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
you should be able to alter the table with something like this
ALTER TABLE claim_incentive_form_data CHANGE id id INT(10)AUTO_INCREMENT PRIMARY KEY;
Just make sure you change the id column and the datatype if yours are diffrent from that.
You have to set the auto_increment setting in the table within mysql.
ALTER TABLE `claim_incentive_form_data` MODIFY COLUMN `your_primary_column` int(4) PRIMARY KEY AUTO_INCREMENT
Refs:
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
http://dev.mysql.com/doc/refman/5.0/en/alter-table.html
you have to set form_id as primary key, auto increment and not null.
If we wanted to show each user which users of the opposite sex have viewed their profile, what would be the best way to keep track of all those views in MySQL?
Each user has a unique userid from the main Users table, which also stores their sex.
We would want to show each user the users that viewed them in order of most recent view to oldest view.
We would obviously not want to show the user themselves if they happened to view their own profile.
We would want to show guys only the girls that viewed them, and the girls only the guys that viewed them.
How would we setup the table of ProfileViews to do that?
What indexes would we use?
What would be the query we would need to show each user who has viewed them?
This is a simple example that I will make for you, hope this helps.
SQL:
CREATE TABLE user
(
user_id BIGINT NOT NULL AUTO_INCREMENT,
sex VARCHAR(10) NOT NULL,
CONSTRAINT PK_USER PRIMARY KEY (user_id)
) ENGINE=INNODB;
CREATE TABLE profileview
(
profileview_id BIGINT NOT NULL AUTO_INCREMENT,
user_id BIGINT NOT NULL,
visitor_user_id BIGINT NOT NULL,
date_time DATETIME NOT NULL,
CONSTRAINT PK_PROFILEVIEW PRIMARY KEY (profileview_id)
) ENGINE=INNODB;
ALTER TABLE profileview
ADD FOREIGN KEY FK_PROFILEVIEW_USER(user_id)
REFERENCES user (user_id);
ALTER TABLE profileview
ADD FOREIGN KEY FK_PROFILEVIEW_VISITOR(visitor_user_id)
REFERENCES user (user_id);
PHP:
This is a simple example of the user profile page - www.domain.com/profile.php?id=xxx.
At this point you need to define two variables in session when the user logs into the site:
$_SESSION['user_id'] (int) / $_SESSION['user_logged'] (boolean)
<?php
if ($_GET && isset($_GET['id']){
if(isset($_SESSION['user_id']){
$profile_user_id = $_GET['id'];
// the user that visits the profile has a session with his/her id on it.
session_start();
$visitor_user_id = $_SESSION['user_id'];
} else {
// if visitor specified an id but there is no session, redirect to login.
header("location: login.php");
}
} else {
// if no id passed redirect to index
header("location: index.php");
}
?>
<html>
<head>
<title>Your title</title>
</head>
<script src="scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
//here you will store the visit with jquery.
$(document).ready(function(){
// store the values from php.
var profile_user_id = <?php echo $profile_user_id ?>;
var visitor_user_id = <?php echo $visitor_user_id ?>;
// here, the user information goes to the visit.php file.
$.post('visit.php' { profile_user_id:profile_user_id, visitor_user_id:visitor_user_id } );
});
</script>
<body>
Here print user information from a SQL select or something of the id passed in the GET.
</body>
</html>
Now, the visit.php file to store data:
<?php
if ($_POST && isset($_POST['profile_user_id']) && isset($_POST['visitor_user_id'])) {
session_start();
// this will end the execution of the script if there is no session from user logged
if ($_SESSION['user_logged'] != true) {
exit();
}
// everything is ok, do the process:
// functions.php contains your SQL connection, I suppose you know how to do it.
include('../cgi-bin/functions.php');
$link = dbconn();
$profile_user_id = mysql_real_escape_string($_POST['profile_user_id']);
$visitor_user_id = mysql_real_escape_string($_POST['visitor_user_id']);
// this will store the data in profileview including date and time if id's are not equal.
if($profile_user_id != $visitor_user_id){
$sql = "INSERT INTO profileview (user_id, visitor_user_id, date_time) VALUES ($profile_user_id, $visitor_user_id, NOW())";
mysql_query($sql, $link);
}
}
?>
EXTRA: if you don't know what functions.php do, here it is:
<?php
function dbconn() {
if(!include_once('db.php')) {
die('Error include file.');
}
if (!$link = mysql_connect($db['hostname'],$db['username'],$db['password'])) {
die('Error connecting.');
}
if (!mysql_select_db($db['database'])) {
die('Error selecting.');
}
return $link;
}
?>
The above file will need this file too: setup here your connection parameters to your db.
db.php
<?php
$db = array(
'hostname' => 'localhost',
'username' => 'root',
'password' => 'mysql',
'database' => 'mydb'
);
?>
I suggest you to put this in the cgi-bin folder of your hosting for better practices as you can see in visit.php file code.
Now, create another file called visitors.php?id=xxx and do a select * from of your profile views according to the user_id. At this point you will be able to:
Get the user_id information and if it is men (for example)...
Select visitors by sex and do a rule to list only female visitors.
List visitors according to the time stored in profileview table.
profileviews:
profile
userwhoviewed
timestamp
Index the profile column.
So when your user views the page, check if it's the profile owner, get the sex of the profile owner, check the sex of the viewer, if different, update the table with the viewer and the timestamp.
When querying the results, just select all rows matching the target profile, ordered by timestamp desc, and iterate to build your links back to those profiles.
I normally use INT data types in these fields (keeps the rows smaller and speeds up the lookups), then have a user table that generates those UID's as an auto_increment primary key. That will hold your gender and preference fields, too, as well as any other ancillary user data, and makes it easier to change login names, if desired.
But you're leaving out your gay users. Better to just log them all and let the user filter based on their preferences. :)
UsersTable
UserID Sex
1 Boy
2 Girl
3 Girl
UsersViewsTable
UserID View Unixtimestamp
1 2 342143243432
1 3 142143243432
2 3 242143243432
3 1 442143243432
When you visite the user profile, you'll use this :
IF CurrentUserSex != UserProfileSex
INSERT INTO UsersViewsTable (UserID, View, Unixtimestamp) VALUES (CurrentUser, CurrentProfileUserID, time)
Now, you want to fetch this on a page to see last seen from opposite sex ?
SELECT * FROM UsersViewsTable LEFT JOIN UsersTable USING (UserID) WHERE Sex != CurrentUserSex GROUP BY View ORDER BY Unixtimestamp DESC
EDIT :
IF CurrentUserSex != UserProfileSex {
$Res = SELECT CurrentProfileUserID FROM UsersViewsTable WHERE UserID = CurrentUserID AND View = UserProfileID LIMIT 1
if($Res['Count'] == 1){
// Exist
UPDATE UsersViewsTable SET Unixtimestamp = time WHERE UserID = CurrentUserID AND View = UserProfileID LIMIT 1
} elseĀ {
// Doesnt exist
INSERT INTO UsersViewsTable (UserID, View, Unixtimestamp) VALUES (CurrentUser, CurrentProfileUserID, time)
}
}
Just check n compare for each user profile page with the visitor id and profile id. If two are different store in a visit table with date and time and your required info. Before inserting just check the table row
if prof id, vistor id already exists then update the time else just insert the data.
Thanks.
I'm trying to make a little project for adding friends.
When you click the add friend button you are sending an Ajax call with the friend id & username (they are the id and name attributes of each add button) to the add.php file.
(The mysql structure is: 1 users table + X tables named the user's name(columns: friendid, ispending))
In the PHP file there are only 2 MySQLi queries: Here is the code for the add file:
session_start();
$friendid = $_POST['id'];
$myname = $_SESSION['username'];
$friendname = $_POST['name'];
$myid = $_SESSION['id'];
$add = new Mysqlconnect();
$add->db->query("INSERT INTO $myname VALUES($friendid, 'yes')");
$add->db->query("INSERT INTO $friendname VALUES ($myid, 'yes')");
$add->db_Close();
The Mysqlconnect class is required i just didn't want the code here to be too long.
Here's the Ajax call:
$('.add').click(function(){
var name = $(this).attr("name");
var id = $(this).attr("id");
$.ajax({
type: "POST",
data: "&name="+name+"&id="+id,
url: 'add.php',
success: function(){
alert("success");
}
});
});
THE PROBLEM :
When I click "add friend" it does alert "success" but only one table gets updated everytime or even no table at all.
Though one time I clicked it and it did work (I did not change the code that time, I tried clicking like every 20 seconds).
How can I solve this?
if i understood you correctly you seem to be creating a new table for each user's friends (1 users table + X tables named the user's name) this isnt a good approach and you'd be better off with just 2 tables: users and user_friends as follows:
drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varbinary(32) unique not null
)
engine=innodb;
drop table if exists user_friends;
create table user_friends
(
user_id int unsigned not null,
friend_user_id int unsigned not null,
created_date datetime not null,
primary key (user_id, friend_user_id) -- note clustered composite PK (innodb only)
)
engine=innodb;
A full example script can be found here : http://pastie.org/1242699
Hope this helps.
please i need come help i have a form of check boxes i want to save the name and value of the boxes that registered user selects into a table ,now i have registered users information saved in a table ,how the table that saves the registered users selection is to be created to have a relation with the table of users????
my registered users table
<?php
$connect=mysql_connect("localhost","root") or die (mysql_error());
mysql_select_db("login") or die (mysql_error());
$query="CREATE TABLE users(
userid int not null auto_increment primary key,
username varchar(20),
password varchar(40),
usertype varchar(20),
firstname varchar(30),
lastname varchar(30),
street varchar(50),
city varchar(50),
country varchar(50),
postcode varchar(10),
gender varchar(6),
dateofbirth date,
telnumber varchar(50),
email varchar(50),
insertdate date,
vals text,
comment text
)";
$result=mysql_query($query,$connect) or die('Cannot Create User');
mysql_close();
print " DataBase created well" ;
?>
Let's say you have table of users like this:
**users**
------------------------------
userid username etc...
1 billy ...
2 joe ...
Now you have to create table like this:
**users_checkboxes**
------------------------------
id user_id name value
1 1 newsletter 1
2 1 send me spam 0
3 2 newsletter 0
4 2 send me spam 0
This information means that billy chosen to receive newsletter and no spam while joe does not want to receive anything.
The key is to have userid from the first table here, this is called foreign key. You can read more about it at Wikipedia.
You might like to reword your question so it's easier to read, here's what I think you meant:
How can I update user's data in the database using a form of checkboxes?
Checkboxes are inputs and will come up like text inputs in your GET or POST array (you're more likely to use POST for this).
E.g.:
<form action="update.php" method="post">
<p><input type="checkbox" name="showDate" /> Show the date on every page.</p>
<p><input type="submit" value="Update user record" /></p>
</form>
Then in your PHP you would use something a little like this:
<?php
// Check form has been submitted
if (isset($_POST['showDate'])) {
// Assuming the user is updating their own profile and their
// user id is registered in a session
$update = 'UPDATE users SET showDate = %d WHERE userid = %d';
// It's better to use prepared statements for this, see http://php.net/mysqli
mysql_query(sprintf($update, $_POST['showDate'], $_SESSION['userid']));
} else {
// show the form
echo $form;
}
Hope this makes sense (and is what you were looking for) - your question was unclear to me.