how can I build this update query - php

I have two values from URL. This is those,
$_GET['a'] // this variable has a email address
$_GET['b'] // this variable has a code to activate my account.
I am trying to create UPDATE query using these two values, but problem is these two values belong to two different tables. email has in contact table and active column has in user table.
This is my code so far:
$q = "UPDATE tutors SET active = NULL
WHERE (active='" . mysqli_real_escape_string($dbc, $_GET['z']) . "')
LIMIT 1";
This code is working for me. but I need to check both values in WHERE clause. Can anybody help me to build this query?
UPDATE :
$q = "UPDATE tutors t, contact c SET t.active = NULL
WHERE t.active = '" . mysqli_real_escape_string($dbc, $_GET['z']) . "'
AND c.email = '" . mysqli_real_escape_string($dbc, $_GET['y']) . "'
AND t.contact_id = c.contact_id
LIMIT 1";
Thank you.

At a guess: something like this would work if your tutors and contacts are linked via a contact_id in the tutors table.
<?php
$q = "UPDATE tutors T, contacts C SET T.active = NULL
WHERE T.active = '" . mysqli_real_escape_string($dbc, $_GET['z']) . "'
AND C.email = '" . mysqli_real_escape_string($dbc, $_GET['a']) . "'
AND T.contact_id = C.contact_id"
but... I would need more information about your database schema to make this a more precise answer.

Related

mysql php cannot use "like" as column header

I am using codeigniter to build an app and I am really far in the code.
I have a table with column headers id, page, user and like. Now the problem is, in the mysql query, I realised I cant use the word like for the column name as its a sql keyword I belive.
I can't change the column name from like to something else because it would mean changing 100s of lines of php code.
Is there something that i can do to overcome the clash of the world like?
here is what I mean
$like_variable = 100;
$query = $this->db->query("SELECT * FROM `table_name`
WHERE id ='" . $qry . "' AND
page = '" . $_SESSION['p_id'] . "' AND
user_id = '" . $_SESSION['user_id'] . "' AND
like = '" . $like_variable . "'
");
// i think i cant use the world like above but I cant change the column header
Any solutions would be much appreciated thanks in advance
In SQL, you can use keywords as column names. Wrap them in ``.
SELECT * from `table_name` WHERE `like` = 100
Change like to:
`like`
Result:
$like_variable = 100;
$query = $this->db->query("SELECT * FROM `table_name`
WHERE id ='" . $qry . "' AND
page = '" . $_SESSION['p_id'] . "' AND
user_id = '" . $_SESSION['user_id'] . "' AND
`like` = '" . $like_variable . "'
");

How do I use INNER JOIN in an UPDATE statement?

I have 2 mysql tables that are joined, in the database, by the descriptionId field.
dataTable.dataId
dataTable.descriptionId
dataTable.userId
dataTable.value
descriptionLookupTable.descriptionId
descriptionLookupTable.descriptionName
In PHP, I am trying to update the field: dataTable.value, when dataTable.descriptionID = Gender and the dataTable.userId = $_SESSION['userId'].
For example in the descriptionLookupTable: descriptionLookupTable.descriptionId = 1 and descriptionLookupTable.descriptionName = Gender. And in the dataTable: dataTable.descriptionID = 1.
I understand the part that deals with the userID by using:
"WHERE dataTable.userId = '" . $_SESSION['userId'] . "'";
But I can't figure out how to use INNER JOIN.
The following query does not work.
$query = "UPDATE dataTable
INNER JOIN descriptionLookupTable
ON dataTable.descriptionId = descriptionLookupTable.descriptionId
AND descriptionLookupTable.descriptionName = Gender
SET Gender = '$gender' WHERE dataTable.user_id = '" . $_SESSION['user_id'] . "'";
The error message is: Unknown column 'Gender' in 'field list'.
Gender apparently is not a column in your table. One of the field must be named Gender for you to be able to update its content
what about trying to update a field which is in your table :) :
SET dataTable.value = '$gender' WHERE dataTable.user_id = '" . $_SESSION['user_id'] . "'";
descriptionLookupTable.descriptionName = Gender
Gender in this case is a string literal, therefore you have to mark it as such
descriptionLookupTable.descriptionName = 'Gender'

Mysql Insert data to table with duplicate data except one field

I am developing a classroom website.
There is a form to insert student profile/data into the database table student.
This site has 5 class groups, IDs as id= 1, 2, 3, 4, 5.
Inserting data to database table succeeds.
But I have a question: Each student must be under classroom 1 and 2, so when we insert data I need the database to automatically create two database results for each times, both results all field are same data except classgroup_id, i mean one result must classgroup_id=1 and second result must be classgroup_id=2, i need mysql automatically generated this for when add each student... any idea.?
this is my table structure
student_id (int) AI
name
email
classgroup_id (default value=1)
user_id
this is my php code for insert data to table
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "'");
thanks... i have only a medium level php knowledge
ClassGroups are in table or just static numbers?
If they are just static numbers, then i think simpliest way is to do another insert with duplicated data. For example for both rows should be:
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "'");
$this->db->query("INSERT INTO " . DB_PREFIX . "student SET user_id = '" . (int)$this->user->getId() . "', name = '" . $this->db->escape($data['name']) . "', email = '" . $this->db->escape($data['email']) . "', classgroup_id =2");
If they are in some table, then you can do insert with one insert(code will be shorter) but with different insert syntax then yours. For example your ClassGroup table is just ClassGroups:
$this->db->query("INSERT INTO " . DB_PREFIX . "student (user_id, name, email, ClassGroup_id)
select " . (int)$this->user->getId() . ", '" . $this->db->escape($data['name']) . "', '" . $this->db->escape($data['email']) . "',ClassGroup_id from ClassGroups where ClassGroup_id=1 or ClassGroup_id=2");
But i think it should be best if you do for each data(student, ClassGroup) different table and do relation table for them, it will not duplicate data and table student will be faster if you gather data from it by primary AI key and not by varchar type column name.
You don't need PHP to do this... Pure SQL pseudosolution:
INSERT INTO student (student_id name, email) SELECT name, email from student where classgroup_id = ?
If you construct a fiddle and leave a comment as to where to find said fiddle, I'd be happy to tweak the query for your specific needs.
In order to avoid duplicate entries for students, you can make another table in which you link the students to their classes.
For example:
Students
student_id (primary key)
name
email
user_id (if still needed...)
Classgroups
classgroup_id (primary key)
classgroup_name
StudentsPerClassgroup
student_id (foreign key)
classgroup_id (foreign key)
You have to keep the record in temporary table first and then do the operations .. try it
//get last insertId
$last_insert_id = $this->db->insert_id();
$new_id = $last_insert_id +1;
$query = "CREATE TEMPORARY TABLE tmp SELECT * FROM yourtable WHERE your_primary_key = $last_insert_id;
UPDATE tmp SET your_primary_key= $new_id,classgroup_id = 2 WHERE your_primary_key = $last_insert_id;
INSERT INTO yourTable SELECT * FROM tmp WHERE your_primary_key = new_id";
$this->db->query($query);
Hope you get some idea

how to limit the amount of comments or replies to comments a user can post per day

I have a comment section and a reply to comment section on my social network. We are having some trouble with manual spammers, and I was going to limit the amount of comments someone could post a day.
Here are the insert queries for comments and reply to comments:
//COMMENTS
$query = "INSERT INTO `CysticAirwaves` (
`FromUserID`,
`ToUserID`,
`comment`,
`status`,
`statusCommentAirwave`,
`date`,
`time`
) VALUES (
'" . $auth->id ."',
'" . $prof->id ."',
'" . mysql_real_escape_string($_POST['ProfileComment']) ."',
'active',
'active',
'" . date("Y-m-d") . "',
'" . date("G:i:s") . "')";
mysql_query($query,$connection);
if($auth->id == $prof->id) {
$just_inserted = mysql_insert_id();
$query = "UPDATE `CysticAirwaves` SET `status` = 'dead' WHERE `FromUserID` = '" . $auth->id . "' AND `ToUserID` = '" . $prof->id . "' AND `id` != '" . $just_inserted . "'";
$request = mysql_query($query,$connection);
}
//REPLIES
$query = "INSERT INTO `CysticAirwaves_replies` (
`AirwaveID`,
`FromUserID`,
`comment`,
`status`,
`date`,
`time`
) VALUES (
'" . mysql_real_escape_string($_POST['comment']) . "',
'" . $auth->id . "',
'" . mysql_real_escape_string($_POST['reply']) . "',
'active',
'" . date("Y-m-d") . "',
'" . date("G:i:s") . "'
)";
mysql_query($query,$connection);
$mailto = array();
/* get the person that wrote the inital comment */
$query = "SELECT `FromUserID` FROM `CysticAirwaves` WHERE `id` = '" . mysql_real_escape_string($_POST['comment']) . "' LIMIT 1";
$request = mysql_query($query,$connection);
$result = mysql_fetch_array($request);
$comment_author = new User($result['FromUserID']);
thanks in advance
You can perform a select to see how many entries are in the table already by that user for the current date:
SELECT COUNT(*)
FROM CysticAirwaves
WHERE userid = $auth->id
AND date = CURDATE()
Then only perform the INSERT if the number is below your threshold. Alternatively, you can place a trigger on the INSERT that does this check with every INSERT and bounces the call as well. ("Best practice" would be to place it in the database as this would be a database-related limitation, but that's your call)
It's been a while since I've done MySQL triggers, but I think think is what you're after:
delimeter |
CREATE TRIGGER reply_threshold BEFORE INSERT ON CysticAirwaves_replies
FOR EACH ROW BEGIN
DECLARE reply_count INT;
SET reply_count = (SELECT COUNT(*) FROM CysticAirwaves_replies WHERE userid = NEW.userid AND `date` = CURDATE());
IF reply_count > 5 THEN
SIGNAL SQLSTATE SET MESSAGE_TEXT = 'Too many replies for today';
END IF;
END;
|
delimeter ;
Essentially, if you go to insert a reply in the table and the threshold has been exceeded, a sql error will be raised stopping the action. You can't "prevent" an insert per-say, but you can raise an exception that makes it fall-through.
You can only limit this by the ip address when you don't have a login system. But the ip can change and this is here the problem.
The best way is to secure the form by a login. That only user can post when they are logged in.
Last technique is to use a captcha like Recaptcha then at most time bots fill out your form and spam to your system.
When you have a login. Then make a table related to your usertable and count the INSERTS. Before you INSERT a new comment check the table if there was a INSERT today.
Before to insert the comment, you check if the user has posted more than 5 comments in the day.
If yes, you don't insert the comment and you display a message.
SELECT COUNT(*) FROM CysticAirwaves_replies WHERE FromUserID = the_user_id AND date = CURDATE()
Besides counting before each insertion, you can store the number of comments made by an user somewhere directly, so you don't have to do the count(*) every time (which can be expensive if an user has lots of comments and the table you have is somewhat big).
Like, on commenting:
SELECT comment_count FROM comment_count_table WHERE user_id = ?
If that value is small enough, you do:
UPDATE comment_count_table SET comment_count = comment_count + 1 WHERE user_id = ?
Be careful with this since you'd need to reset that counter somehow.
At my company we implemented this setting a "last modified field". When we do the SELECT, if the "last modified day" is not today, then we reset the counter.
Another option is to have a cron job that resets the counter for all users once every day, but that is way too expensive.

sql statement works in phpMyAdmin but won't work in mysql_query

Really stuck on something. I'm trying to update a database and the code looks write - and if I echo it out and paste it directly into phpMyAdmin it works perfectly - but the code itself doesn't work... I have spend a day so far trying to figure out why it's not working and I'm completely out of ideas...
function restoreSession()
{
mysql_connect("theHost", "root", "rootPWD") or die(mysql_error());
mysql_select_db("myDatabase") or die(mysql_error());
$restore_cmd = 'UPDATE wp_dor_cart66_sessions SET user_data = (SELECT user_data FROM wp_dor_cart66_stored_sessions WHERE ip_address = "' . $_SERVER['REMOTE_ADDR'] . '")';
$clean_up = "DELETE FROM `wp_dor_cart66_sessions` WHERE `ip_address` = \"" . $_SERVER['REMOTE_ADDR'] . "\" AND id NOT IN (SELECT id FROM ( SELECT id FROM `wp_dor_cart66_sessions` ORDER BY id DESC LIMIT 1 ) user_data )";
mysql_query($clean_up) or die('Query failed: ' . mysql_error());
$result = mysql_query($restore_cmd) or die('Query failed: ' . mysql_error());
echo "<br/>";
echo $restore_cmd;
echo "<br/>";
var_dump($result);
echo "<br/>";
print_r($result);
}
The resulting output looks like:
UPDATE wp_dor_cart66_sessions SET user_data =
(SELECT user_data FROM wp_dor_cart66_stored_sessions
WHERE ip_address = "196.54.110.24");
bool(true)
1
It doesn't appear to have any errors - but I just can't get it to update. If it didn't work in phpMyAdmin - I'd know there was something wrong with the SQL - but it seems right... I'm just really out of ideas - any help would be greatly appreciated!
Here are the statements again with some formatting:
$restore_cmd = '
UPDATE
wp_dor_cart66_sessions
SET
user_data = (
SELECT
user_data
FROM
wp_dor_cart66_stored_sessions
WHERE
ip_address = "' . $_SERVER['REMOTE_ADDR'] . '"
)
';
$clean_up = "
DELETE FROM
`wp_dor_cart66_sessions`
WHERE
`ip_address` = \"" . $_SERVER['REMOTE_ADDR'] . "\"
AND id NOT IN (
SELECT
id
FROM
(
SELECT
id
FROM
`wp_dor_cart66_sessions`
ORDER BY
id DESC
LIMIT
1
) user_data
)
";
$restore_cmd = 'UPDATE wp_dor_cart66_sessions SET user_data = (SELECT user_data FROM wp_dor_cart66_stored_sessions WHERE ip_address = \"' . $_SERVER['REMOTE_ADDR'] . '\")';
need to escape the quotation marks
Looks like quoting error, Try this:
"UPDATE wp_dor_cart66_sessions SET user_data = (SELECT user_data FROM wp_dor_cart66_stored_sessions WHERE ip_address = '" . $_SERVER['REMOTE_ADDR'] . "')";
If could be that you have multiple results in your SELECT.
What if you do ...
$restore_cmd = 'UPDATE wp_dor_cart66_sessions SET user_data = (SELECT user_data FROM wp_dor_cart66_stored_sessions WHERE ip_address = "' . $_SERVER['REMOTE_ADDR'] . '" LIMIT 1)';
... note the LIMIT 1
Are you sure that the first query is not deleting all the matching rows?
I don't understand the "user_data" part at the end of the first query. But I would check the number of affected rows after each query to see if query is doing any affect on data and if it is, is it doing well or there's just some logical mistake.

Categories