Im having trouble with my sql statements. I dont know what im doing wrong but it keeps adding to the database much rather than uploading
$result = mysql_query("SELECT id FROM users where fbID=$userID");
if (mysql_num_rows($result) > 0) {
mysql_query("UPDATE users
SET firstName='$firstName'
, lastName='$lastName'
, facebookURL='$link'
, birthday='$birthday'
, update='$today'
, accessToken='$accessToken'
, parentEmailOne='$parentEmailOne'
, WHERE fbID='$userID'");
} else {
mysql_query("INSERT INTO users
(fbID, firstName, lastName, facebookURL, birthday
, updated, accessToken, parentEmailOne )
VALUES ('$userId', '$firstName', '$lastName', '$link', '$birthday'
, '$today', '$accessToken', '$parentEmailOne')");
}
i see that in the first query you use $userID , while in the INSERT you are using $userId
There is an extra comma in your first (I mean the UPDATE) query:
'... $parentEmailOne', WHERE fbID='$userID'");
^
You have an extra comma in your UPDATE statement before the WHERE clause:
parentEmailOne='$parentEmailOne', WHERE fbID='$userID'"
^^^^
But, also you should make sure that your variable $userID isn't empty and echo out mysql_num_rows() to see what you're getting back from the SELECT
Also, in your SELECT you use the variable $userID but in your INSERT you are using $userId. Note the capitalization difference.
You need quotes on the first query, fbID='$userID'
Also, you dont need this , before where, on the second SQL
And last, you use userID on the first reference, and userId on the last
Do the names contain any apostrophes?
You'll want to be sure to use mysql_real_escape_string
Are you saying it inserts rather than updating? In other words, it's failing to find existing records that you expect it to find?
I recommend that instead of doing "update if the record exists, otherwise insert" logic yourself, you look into MySQL's built-in functionality.
update is keyword and you must use from delimiter.
and one comma in first query is extra
$result = mysql_query("SELECT `id` FROM `users` where `fbID`=$userID");
if (mysql_num_rows($result) > 0) {
mysql_query("UPDATE `users` SET `firstName`='$firstName', `lastName`='$lastName', `facebookURL`='$link', `birthday`='$birthday', `update`='$today', `accessToken`='$accessToken', `parentEmailOne`='$parentEmailOne' WHERE `fbID`='$userID'");
} else {
mysql_query("INSERT INTO `users` (`fbID`, `firstName`, `lastName`, `facebookURL`, `birthday`, `updated`, `accessToken`, `parentEmailOne` ) VALUES ('$userId', '$firstName', '$lastName', '$link', '$birthday', '$today', '$accessToken', '$parentEmailOne')");
}
this is standard code
if the userID column is a varchar, you should quote the $userID variable in your first query
Related
I've tried to follow several answers on this question but can't seem to get it to work for my specific problem.
I want to insert data but only if the flight_number doesn't exists already. How can I do that?
$sql = mysqli_query($con,
"INSERT INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Rob since you saying flight_number is a unique then you can use INSERT IGNORE
<?php
$sql = "INSERT IGNORE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`) VALUES (?,?,?,?)";
$stmt = $con->prepare($sql);
$stmt->bind_param('isss',$flight_number,$mission_name,$core_serial,$payload_id);
if($stmt->execute()){
echo 'data inserted';
// INSERT YOUR DATA
}else{
echo $con->error;
}
?>
OR you could select any row from your database that equal to the provided flight number then if u getting results don't insert.
$sql = "SELECT mission_name WHERE flight_number = ? ";
$stmt = $con->prepare($sql);
$stmt->bind_param('i',$flight_number);
if(mysqli_num_rows($stmt) === 0){
// INSERT YOUR DATA
}
A unique index on flight number should do the trick.
CREATE UNIQUE INDEX flight_number_index
ON space (flight_number);
If you want to replace the existing row with the new one use the following:
$sql = mysqli_query($con,
"REPLACE INTO space (`flight_number`, `mission_name`, `core_serial`, `payload_id`)
VALUES ('".$flight_number."', '".$mission_name."', '".$core_serial."', '".$payload_id."')"
);
Make note that I just copied your code and changed INSERT to REPLACE to make it easy to understand. PLEASE PLEASE PLEASE do not use this code in production because it is vulnerable to injection.
If you don't want to replace the existing row, run an insert and check for errors. If there is an error related to the index, the row already exists.
Disclaimer: I haven't tested any of this code, so there may be typos.
I'm working on a script, but it won't work.
When a user makes a post, NOW() will be inserted. I want to make a script where the user will only be able to make a post when his last post differs at least 10 minutes from the post he wants to make at this moment. I don't want to make use of cookies, seeing people can delete them.
I have this code at the moment, but don't know how to move on. Thank you!
if ($db_found) {
$sql1="SELECT send_time FROM bloopp WHERE email='$email' ORDER BY id DESC LIMIT 1";
while($row = mysqli_fetch_array($result)) {
$last_post = $row['send_time'];
}
if ($last_post + 600 >= NOW() {
sql2 = "INSERT INTO bloopp (bloopp, browser, medium, send_time, email) VALUES
('$bloopp', '$browser', 'desktop', NOW(), '$email')";
$result = mysql_query($sql);
if($result) {
header('Location: index.php');
}
else {
echo "ERROR";
}
}
}
When dealing with time, it's handy if you can rely entirely on the database. This avoids mixing up the database conception of time with PHP's, which may be on different servers and/or have different time configuations.
So, try to locate a post made in the last ten minutes, and if there isn't one, you know you are good to go
SELECT COUNT(*) AS recent_posts
FROM bloopp
WHERE email=? AND (UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(send_time))<600;
on the query you have :
sql2 = "INSERT INTO bloopp (bloopp, browser, medium, send_time, email) VALUES ('$bloopp', '$browser', 'desktop', NOW(), '$email')";
$result = mysql_query($sql);
shouldn;t that be
$sql = "INSERT INTO bloopp (bloopp, browser, medium, send_time, email) VALUES ('$bloopp', '$browser', 'desktop', NOW(), '$email')";
mind the sql2 / $sql replacement
Lets say you have table user
user_table:
id
email
bloop:
email
browser
....
Select * from user_table left join ( select max(send_time),email from bloop where email=$email ) max_sel on max_sel.email = user_table.email...
Something like this will get the user with his latest post (or null for new users who do not have a post, check put left joins), put the date in session and when he posts update it and such, you know how to do this.
Regards
I'm trying to get the row ID after the slug (ex. post 1 returns "/bligpost.php?id=1").
Instead, it returns no ID.
Where am I doing it wrong? (I have included my other attempts in comments.)
mysql_connect("$hosty","$uname","$paswd");
#mysql_select_db($dbnme) or die( "Unable to select database");
$name=$_POST['Title'];
$slug="blogpost.php?id=";
$auth=$_POST['Author'];
$date=$_POST['Date'];
$cont=$_POST['Content'];
//$query = ("INSERT INTO Blogs (Name, URL, Content, Author, Date) VALUES ('$name', '$slug', '$cont', '$auth', '$date')");
mysql_query("INSERT INTO Blogs (id, Name, URL, Content, Author, Date) VALUES (NULL, '$name', '$slug', '$cont', '$auth', '$date')");
//$pind = mysql_query("SELECT LAST_INSERT_ID()");
mysql_query("UPDATE Blogs SET URL=blogpost.php?id=`id` WHIERE id=LAST_INSERT_ID()");
//mysql_query("UPDATE Blogs SET URL=blogpost.php?id=".$pind." WHERE Content=".$cont);
mysql_close();
Try with mysql_insert_id() like
mysql_query("INSERT INTO Blogs (id, Name, URL, Content, Author, Date) VALUES (NULL, '$name', '$slug', '$cont', '$auth', '$date')");
$id = mysql_insert_id();
echo "My Last Inserted Id ".$id;
Tr this LINK And dont use mysql_* functions due to they are depricated,instead of it,use mysqli_* or PDO statements
And try to update your update query like
mysql_query("UPDATE Blogs SET URL = 'blogpost.php?id=$id' WHERE id=$id");
EDIT Based on your commented query try like
mysql_query("UPDATE Blogs SET URL=blogpost.php?id=$pind WHERE Content='".$cont."'")
or
mysql_query("UPDATE Blogs SET URL=blogpost.php?id=$pind WHERE Content='$cont'")
What you're actually doing wrong in the commented line when assigning to $pind is you expect the mysql_query to return your new id, but what it actually returns is a resource from which you must get the id using mysql_fetch_row or any similar function from the mysql_fetch_ family.
As for the uncommented row with WHIERE id=LAST_INSERT_ID(), it would probably work, but you're not concatenating the prefix string with your id. You should do it like this:
mysql_query("UPDATE blogs SET url = CONCAT('blogpost.php?id=', id) WHERE id = LAST_INSERT_ID()");
On the other hand I don't approve of your design of holding your urls in the database when you already have everything you need in the database (i.e. the id), so you should just prepend the "blogpost.php?id=" to the id you get when selecting that row and you're all set, this url of yours is completely unnecessary.
Oh and people are correct when they say this is deprecated, but it seems you're still learning so this is probably a little easier to grasp than the mysqli approach so you can stick with it for now and move up to mysqli once you're comfortable.
Hope that helps. Good luck.
How about this?
$pind = mysql_insert_id();
http://php.net/manual/en/function.mysql-insert-id.php
$id = mysql_insert_id();
In table id field should be auto increment field
I am having some problems with a script, I am basically inputting data into a MySQL table. This data will be inserted in the table as 1 row.
Upon a row of data being entered into the table I want the current/specific row currently being entered to have the column 'account_type' to be updated from its default value 'member' to 'client'.
It's a long story why I need to do it this way but I do not want to simply just enter the value 'client' it must be updated from 'member' to client.
The script I have (which is the bit at the bottom) is currently doing just this but it is affecting all rows in the table, is there a way I can add a where clause to the update to say only affect the current row being entered and do not update all other rows in the table?
<?php ob_start();
// CONNECT TO THE DATABASE
require('../../includes/_config/connection.php');
// LOAD FUNCTIONS
require('../../includes/functions.php');
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$number = $_POST['number'];
$dob = $_POST['dob'];
$accounttype = $_POST['accounttype'];
$query="INSERT INTO ptb_registrations (
username,
password,
firstname,
lastname,
email,
number,
dob,
accounttype,
date_created )
VALUES(
'".$username."',
'".$password."',
'".$firstname."',
'".$lastname."',
'".$email."',
'".$number."',
'".$dob."',
'".$accounttype."',
now()
)";
mysql_query($query) or die();
$query="INSERT INTO ptb_users (
first_name,
last_name,
email,
password )
VALUES(
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";
mysql_query($query) or dieerr();
$result = mysql_query("UPDATE ptb_users SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'");
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You can use the MySQL function LAST_INSERT_ID() to do this.
The old ext/MySQL extension exposes this functionality through mysql_insert_id(), but you can also access it directly, and more cleanly, and safely, in a query.
So you can do something like this:
$result = mysql_query("
UPDATE ptb_users
SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'
WHERE id = LAST_INSERT_ID()
");
I know you say "it's a long story..." But what you are doing makes little-to-no sense. I can only imagine you are doing this because of a trigger - and that demonstrates quite nicely why triggers are generally a bad idea ;-)
Please try and re-think your design if at all possible.
Get the inserted ID after your first query then use it in the update (assuming you have a primary key with auto-increment).
Try With WHERE Condition on unique coloumn
mysql_query("UPDATE ptb_users SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'" WHERE ptb_user.email='$email');
I am taking a calendar feed with a PHP file and I need to compare it to my database. If the $lastEdited variable is different than what is in the database, I need to change the record. I'm really new to SQL, so I'm not sure what to do. I just have Date_Edited set as a VARCHAR so I just need to compare the strings. I have this:
$query = "SELECT * FROM myTable WHERE Event_ID='$id'";
$result = mysql_query($query);
if (!mysql_num_rows($result)) {
mysql_query("INSERT INTO myTable (Event_ID, Date_added, Date_edited, Title)
VALUES ('$id', '$dateAdded', '$lastEdited', '$title')");
}
How do I compare $lastEdited to Date_edited and change the row if they are different?
you need to do something like
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($lastEdited != $row['Date_added']){
# run update query
mysql_query("update myTable set
// here insert all update fields you need like
Date_added = '$dateAdded', Date_edited = '$lastEdited' , Title = '$title'
WHERE Event_ID='$id' ");
}
You probably want to use the UPDATE statement.