Check whether data is at table - php

I asked something about in_array() and I already got that working. But now I have a different problem:
I have a table that says which services are assigned to hosts: services_hosts(service_id, host_id).
How can I see if the service that is selected is already assigned to that host, also selected? Basically, I want to see if the specific line (service_id, host_id) already exists in that table.
EDIT:
The problem is that I want to compare in a separate file that has functions that connect to DB:
function addServiceToHost($service_name, $host_id)
{
$query = "INSERT INTO monitoring_hosts_services (service_id, host_id) values ((SELECT service_id FROM monitoring_services WHERE name = '".$service_name."'), '".$host_id."')";
$result = #pg_exec($this->conn, $query);
if ($row = pg_fetch_row($result))
{
"blabla error msg"
exit;
}
return $this->parseResultObj($result);
}

I might not unserstand your question correctly but would this do the trick:
SELECT * FROM ServerHostsTable WHERE service_id = '5' AND host_id = '8'

$query = ("SELECT * FROM ServerHostsTable WHERE service_id = '5' AND host_id = '8'")
if(mysql_num_rows($query)>0)
{
//the item is in the db
}
else
{
//not in the db
}
hope this helps

your question is not very clear, but from what I understand you want to test if a specific row is inserted into a database table. you could do this like this:
$result=mysql_query("SELECT service_id FROM services_hosts WHERE service_id=$theserviceid AND host=$thehostid");
if($row=mysql_fetch_row($result){
echo "already in the db";
} else {
echo "not in the db!";
}

I would run this query.
$sql = "SELECT COUNT(*) AS ret\n";
$sql.= "FROM services_hosts\n";
$sql.= "WHERE service_id = $service_id\n";
$sql.= "AND host_id = $host_id";
The result should be one row with one field (named ret):
0 - the service is not present on the host
1 - service is present on the host
enything else - there is a problem with table in database

Related

How to check if the DB already have the data or insert new data

What I want is that php check if the client IP address is the same one which in the DB if it already exists, if not to insert new data.
well, it works if the client isn't already inserted in the database, but if he already exists php is skipping the update and trying to insert it again in the database............
I don't know whats wrong with it and couldn't figure out.
Here is my code:
<?php
$corruser = $_SESSION['user_name'];
$client_ip = $_SERVER['REMOTE_ADDR'];
require_once 'connections/dbc.php';
if (!$conn) {
echo "Error connecting the database";
exit();
} else{
$GUI = "SELECT * FROM `customers` WHERE user_name='$corruser'";
$GUI_response = mysqli_query($conn, $GUI);
if (!$row = mysqli_fetch_assoc($GUI_response)) {
echo "Error while query the database";
exit();
} else{
$customer_id = $row['customer_id'];
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$check_response = mysqli_query($conn,$check);
$check_result = mysqli_fetch_array($check_response, MYSQLI_NUM);
if ($check_result[0] > 1) {
$update_ip = "UPDATE `users-ipdb` SET `client_ip`='$client_ip' WHERE customer_id='$customer_id' AND user_name='$corruser' ";
$update_ip_result = mysqli_query($conn, $update_ip);
if (!$update_ip_result) {
echo "ERROR UPDATING DATA BASE";
exit();
}
} else{
$insert_new = "INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`) VALUES ('$customer_id','$corruser','$client_ip')";
$insert_new_result= mysqli_query($conn, $insert_new);
if (!$insert_new_result) {
echo "Error inserting new data in the database";
exit();
}
}
}
}
?>
I think you made an error with this code :
$check = "SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='$user_name' ";
$user_name variable doesn't exist, you should replace it with $corruser
That's why the code never goes into the UPDATE
First, make sure that your condition does work as expected. If customer_id is not a number the following line:
if ($check_result[0] > 1) {
can be possibly evaluated as if(0 > 1) let you read this:
Comparing String to Integer gives strange results.
The other comments mention "UPSERTS" which are explained here https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/
The basic idea is that you can do
INSERT INTO `users-ipdb`(`customer_id`, `user_name`,`client_ip`)
VALUES ('$customer_id','$corruser','$client_ip')"
ON DUPLICATE KEY UPDATE client_ip='$client_ip';
and you get rid of the all the php logic. For this to work properly customer_id and user_name must be both part of the PRIMARY KEY.
If you need to query multiple tables, you can use joins - if you use ON DUPLICATE KEY UPDATE you don't need them, but still a good thing to know - https://mariadb.com/kb/en/library/join-syntax/
Last, but not least - it is a good habit to escape any value which may come from other sources. Maybe it is not your case, but some people tend to create usernames like Joe';DROP TABLE mysql.user;SELECT ' and it will destroy your database, because your query will become
SELECT * FROM `users-ipdb` WHERE customer_id='$customer_id' AND user_name='Joe';DROP TABLE mysql.user;SELECT ''
So be careful.

error in subject registration

I'm facing a problem here. First off, what I'm doing here is subject registration system for students. I've set a part of code to limit the same student from registering the same subject again and again. But sadly, that has given me a reversed effect. My error is that when a student registered a subject, other students can't register that particular subject even though they have never registered it before. Any help would be much appreciated.
<?php
if(!isset($_POST['submit'])){
exit('Unauthorized access!');
}
$name = $_POST['name'];
$studentid = $_POST['studentid'];
$program = $_POST['program'];
$fintake = $_POST['fintake'];
$courseid = $_POST['courseid'];
include("include/config.php");
//this could be the problem,i'm not sure
$check_query = mysqli_query($link, "SELECT r_id FROM course_registration WHERE r_cid='$courseid' limit 1");
if(mysqli_fetch_array($check_query))
{
echo 'Error:Course ID:',$courseid,' already exists. Return';
exit;
}
$result = mysqli_query($link, "SELECT * FROM course_list WHERE c_cid = '$courseid'");
if(mysqli_fetch_array($result))
{
$sql = "INSERT INTO course_registration (r_name,r_sid,r_program,r_fintake,r_cid) VALUES('$name','$studentid','$program','$fintake','$courseid')";
if(mysqli_query($link,$sql))
{
exit('Success! Register course successfully. Homepage');
}
else
{
echo 'Sorry! Add data failed:',mysqli_error($link),'<br />';
echo 'Click here Return retry';
}
}
else
{
echo 'Sorry! Wrong course id.','<br />';
echo 'Click here Return retry';
}
?>
Database: course_registration
r_id r_name r_sid r_program r_fintake r_cid
1 TAN KOON ENG 0187904 DIP-CS 01-2015 DTP-3033
2 TAN KOON ENG 0187904 DIP-CS 01-2015 DCS-22104
3 CRISTIANO RONALDO 0190007 DIP-GT 09-2016 DGP-2254
4 CRISTIANO RONALDO 0190007 DIP-GT 09-2016 DGA-1224
Your checking courseid is exists in table but need to check courseid is exists for particular student so you need to add where clause like this
SELECT r_id FROM course_registration WHERE r_cid='$courseid' AND r_sid='$studentid'"
you can try this add and studentid in where
$check_query = mysqli_query($link, "SELECT r_id FROM
course_registration WHERE r_cid='$courseid' AND r_sid='$studentid'");
In your given case, you are checking the course id in the database and limiting to 1 only hence, it reports an error in your case. To check whether a student has enrolled into course or not. You must also check the student id with courseid. Maybe, this query might help you:
SELECT r_id FROM course_registration WHERE r_sid='$studentid' AND r_cid='$courseid'"

php sql UPDATE with nested FROM (SELECT)

After hours of trying I need your advice.
I want to combine rows from 2 tables.
After I created a new row in table1 I want to find a row in table2 and combine some of the fields.
If I put the nested SELECT in the SET function
(SET postcode=(SELECT etc)
is works, but if I put it in the FROM function is gives an Error that the syntax is wrong
my code:
$sql = "INSERT INTO instanties(institution, category, postcode)
VALUES('$emapData[0]', '$emapData[1]', '$emapData[2]')";
if ($conn->query($sql) === TRUE) {
//get last added id
$last = $conn->insert_id;
//define WHERE function
$where="postcode_id=$postcode_id AND (minnumber <= $number AND maxnumber >= $number)";
//UPDATE last added row in table with info from other table
$sql2 = "UPDATE instanties
SET postcode_id=pc.postcode_id
FROM
(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1
) pc
WHERE id=$last";
$result = $conn->query($sql2);
if ($result) {
echo 'update is done<br/><br/>';
}
}
else {
echo "Error: " . $sql2 . "<br>" . $conn->error.'<br/><br/>';
}
}
else {
echo "Error: " . $sql . "<br>" . $conn->error.'<br/><br/>';
}
That's not a valid MySQL syntax. You cannot add a "FROM" clause to an UPDATE statement.
http://dev.mysql.com/doc/refman/5.0/en/update.html
However, what you want to accomplish is still possible this way:
$sql2 = "UPDATE instanties
SET postcode_id=
(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1
)
WHERE id=$last";
As long as there is only 1 result from the nested SELECT (and your LIMIT 1 kinda does that).
EDIT:
If you need many fields from the postcode table, you can join on it:
$sql2 = "UPDATE instanties as i
JOIN (
SELECT *
FROM postcode
WHERE $where LIMIT 1
) as pc
SET i.postcode_id=pc.postcode_id
WHERE i.id=$last";
We would usually use an "ON" clause with the join, but since you're only updating 1 row and your nested SELECT will also only return 1 row, it's not necessary.
try this:
$sql2 = "UPDATE instanties
SET postcode_id=(
SELECT postcode_id
FROM postcode
WHERE $where LIMIT 1)
WHERE id=$last";

Implementing facebook-style "unlike" function

I've recently implemented a custom liking and disliking feature for my comics site. I'd like to give users the ability to "Take back" their selection by "unclicking" the like or dislike button.
My function works by:
1) Passing button value (id = 'like' or id = 'dislike') via Jquery to
php script
2) script will first check if an ip exists in the database against
that given comic id... if not it will insert user's IP and current
comic ID... if it does, it originally said "you've already voted"... but now to implement "unliking", I will just have it run a delete query
3) then it will get total current likes for that comic id and
increment.
The way I think it can be done is if the user presses the button again, I basically run the opposite query... delete that user's vote from the table given that comic id... then decrement total likes for that image in the comics table.
So my questions are,
1) Is doing an insert query if they press a button once, then a delete
query if they "deselect" that same choice the best way to implement
this? Couldn't a user spam and overload the database by continuously
pressing the like button, thereby constantly liking and unliking?
Should I just implement some sort of $_SESSION['count'] for that ID?
2) If I'm storing a certain IP... what happens if several uniques
users happen to use the same computer at... let's say a netcafe... it
will always store that user's IP. Is storing against the IP the best
way to go?
Code if you need a reference:
<?php
include 'dbconnect.php';
$site = $_GET['_site'];
$imgid = intval($_GET['_id']);
$input = $_GET['_choice'];
if ($site == "artwork") {
$table = "artwork";
}
else {
$table = "comics";
}
$check = "SELECT ip, tablename, imgid FROM votes WHERE ip = '".$_SERVER['REMOTE_ADDR']."' AND tablename = '$table' AND imgid = $imgid";
$result = $mysqli->query($check);
if ($result->num_rows == 0) {
//Insert voter's information into votes table
$sql = "INSERT INTO
votes (ip, tablename, imgid)
VALUES
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)
ON DUPLICATE KEY UPDATE
imgid = VALUES(imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
/*while ($row = $result->fetch_assoc()) {
echo "you've inserted: " . $row['ip'] . ", " . $row['tablename'] . ", " . $row['imgid'] . ".";
}*/
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") {
$sql = "UPDATE $table SET like_count = like_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes++;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count + 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes++;
}
}
else { //"unlike" their previous like for that given image id
$sql = "DELETE FROM
votes
WHERE (ip, tablename, imgid) =
(\"".$_SERVER['REMOTE_ADDR']."\", \"$table\", $imgid)";
if (!$mysqli->query($sql)) printf("Error: %s\n", $mysqli->error);
$result = $mysqli->query("SELECT like_count, dislike_count FROM $table WHERE id = $imgid");
//put the counts into a list
list($likes, $dislikes) = $result->fetch_array(MYSQLI_NUM);
if ($input == "like") { //remove like
$sql = "UPDATE $table SET like_count = like_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$likes--;
}
else if ($input == "dislike") {
$sql = "UPDATE $table SET dislike_count = dislike_count - 1 WHERE id = $imgid";
$mysqli->query($sql);
$dislikes--;
}
}
echo "Likes: " . $likes . ", Dislikes: " . $dislikes;
mysqli_close($mysqli);
?>
1) I would say yes, use a count feature to limit the number of attempts they can hit the button in succession. Probably wouldn't have much trouble unless they hit really high numbers, I believe a simple loop would do fine.
2) I would not store just the IP. I would try and use something more than just the IP as an Identifier, like the IP and the session cookie - that way it's unique. However on the look back to the server you would have to parse the entry from the db. Or perhaps the mac address. I'm not sure if you have access to that or not. How can I get the MAC and the IP address of a connected client in PHP?
I'm sure there's another way but conceptually that's how I see it working.

mysql compare table values

I am creating a poll in php. I have a table with an id column.
When a user submits a choice, I want the php to first query the database and check whether the table "id" has the id of the current user.
I am pretty new at mysql, can someone help me with the query?
Try this:
$q = "SELECT id FROM table WHERE id = '".mysql_real_escape_string($_POST['user_id'])."'";
$r = mysql_query($q);
if(mysql_num_rows($r) > 0) {
echo "User ID was found in table";
} else {
echo "User ID was not found in table";
}
$qryResult = mysql_query("SELECT userid FROM idtable WHERE userid='$theIdOfUser'");
if (mysql_num_rows($qryResult) == 0)
{
// add a new vote
}
else
{
// notify the user that double voting is prohibited
}
Try not to use names like "id" to avoid conflicts with reserved words and related complications and need to use quotes

Categories