If nothing is found for field, create new field - php

PHP newbie here
I have a mysql table called "topics", and i'm pulling information from the table for a page based on a result from a form (in the URL through GET)
If the URL doesn't exist, i'd like to be able for the table to create a new entry with the topic name from the URL filled in
$topic_name would be what i'd be putting in the new topicname field
My code so far:
$topic_name = strtolower(mysql_real_escape_string($_GET['t']));
//look for info
$topic_info = mysql_query("SELECT * FROM topics WHERE topicname = '$topic_name' LIMIT 1");
if (mysql_numrows($topic_info)<=0) {
//insert record
$SQL='insert into topics (topicname) values ("'.$topic_name.'")';
mysql_query($SQL);
$t_desc='NEW TOPIC : '.$topic_name;
}
else {
//do as normal (without unnessecary loop)
$g=mysql_fetch_array($topic_info);
$t_desc = $g['desc'];
}
EDIT: Sorry, I don't think i explained well, the result is from a GET from a form, so url.com/topic?=BLAH
blah would be the name of the field i'd want to create if it doesn't exist.
The table has an Auto incrementing 'ID' (primary key)

If i understand you correct :
$topic_name = (isset($_GET['t'])) ? strtolower(mysql_real_escape_string($_GET['t'])) : '';
//look for info
$topic_info = mysql_query("SELECT * FROM topics WHERE topicname = '$topic_name' LIMIT 1");
if (mysql_num_rows($topic_info)<=0) {
//insert record
//UPDATE
//$SQL='insert into topics (topicname) values ("'.$topic_name.'")';
$SQL='insert into topics (topicname, `desc`) values '.
'("'.$topic_name.'", "NEW TOPIC DESC")';
mysql_query($SQL);
$t_desc='NEW TOPIC : '.$topic_name;
} else {
//do as normal (without unnessecary loop)
$g=mysql_fetch_array($topic_info);
$t_desc = $g['desc'];
}

Try as below
$topic_info = mysql_query("SELECT * FROM topics WHERE topicname = '$topic_name' LIMIT 1");
$count = mysql_num_rows($topic_info);
if($count <= 0){
// do insert query
}
else {
// loop through you result and display record
while($g = mysql_fetch_array($topic_info)){
$t_desc = $g['desc'];
}
}
Note: Better to use PDO or Mysqli lib for new development and prevent mysql injection attack

Related

MySQL / PHP - How to match an author id to a user id and display username

another question. I need to display a username and so what I'm doing is getting the author id (which is '1'), and then using a query saying get the username from the users table where the author id is the same as the user id.
My problem is that I'm getting the value of '1' returned as I've said above and the following is my code. Am I missing something here or...?
$users = mysqli_query($sql, "SELECT * FROM users WHERE userid = '$authorid'") or die($users . "<br/>" . mysqli_error($sql));
while($userData = mysqli_fetch_array($users)) {
$postAuthor = $usersData['username'];
}
Edit 1
I said also mention the above information should show the name 'Dan'.
The user 'Dan' has a user id of 1 should the author id should be 1 (which it is) from the post row. This is the only use of anything to do with the user table so it's not being overridden anywhere. I'm so confused.
This should have been an error:
while($userData = mysqli_fetch_array($users)) {
^^ no s
$postAuthor = $usersData['username'];
^^ used different variable name
}
Note: Use prepared statements also in this case, you're using mysqli anyways.
$select = $sql->prepare("SELECT * FROM users WHERE userid = ?");
$select->bind_param('i', $author_id);
$select->execute();
$results = $select->get_result();
while($userData = $results->fetch_assoc()) {
$postAuthor = $userData['username'];
}

Why this if else condition is not working properly?

I am using if else condition with foreach loop to check and insert new tags.
but both the conditions(if and alse) are being applied at the same time irrespective of wether the mysql found id is equal or not equal to the foreach posted ID. Plz help
$new_tags = $_POST['new_tags']; //forget the mysl security for the time being
foreach ($new_tags as $fnew_tags)
{
$sqlq = mysqli_query($db3->connection, "select * from o4_tags limit 1");
while($rowq = mysqli_fetch_array($sqlq)) {
$id = $rowq['id'];
if($id == $fnew_tags) { //if ID of the tag is matched then do not insert the new tags but only add the user refrence to that ID
mysqli_query($db3->connection, "insert into user_interests(uid,tag_name,exp_tags) values('$session->userid','$fnew_tags','1')");
}
else
{ //if ID of the tag is not matched then insert the new tags as well as add the user refrence to that ID
$r = mysqli_query($db3->connection, "insert into o4_tags(tag_name,ug_tags,exp_tags) values('$fnew_tags','1','1')");
$mid_ne = mysqli_insert_id($db3->connection);
mysqli_query($db3->connection, "insert into user_interests(uid,tag_name,exp_tags) values('$session->userid','$mid_ne','1')");
}
}
}
i think you are inserting
$r = mysqli_query($db3->connection, "insert into o4_tags(tag_name,ug_tags,exp_tags)
values('$fnew_tags','1','1')");$mid_ne = mysqli_insert_id($db3->connection);
and then you are using while($rowq = mysqli_fetch_array($sqlq))
which now has records you just inserted therefore your if is executed
I'm pretty sure the select query below will always return the same record.
$sqlq = mysqli_query($db3->connection, "select * from o4_tags limit 1");
I think most of the time it will goes to the else, which execute the 2 insert.
Shouldn't you write the query like below?
select * from o4_tags where id = $fnew_tags limit 1

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.

Seeing if variable is in array

I am using a MySQL database. I am completely sure that the ID does actually exist in the database. Why is it going to the last else (where is says //incorrect id) ?
<?php
//Localise user id.
$userid = $_SESSION['userid'];
//Get content of the article.
$sql = "SELECT * FROM articles WHERE creatorid = '$userid'";
$result = mysql_query($sql) or die(mysql_error()); //Execute. If fails, show error.
$array = mysql_fetch_array($result);
if(in_array($articleid, $array)) //If the URL id exists in the database (array)
{
//The article does actually exist for that user. They requested it.
$sql = "SELECT * FROM articles WHERE id = '$articleid'";
$result = mysql_query($sql) or die(mysql_error()); //Execute. If fails, show error.
$array = mysql_fetch_array($result);
$content = $array['content'];
if($content != '') //If the article has actually been written.
{
include($_SERVER['DOCUMENT_ROOT'] . '/includes/renderimage.php');
} else
{
//Article actually hasn't been written.
}
} else
{
//Incorrect ID.
}
?>
You're only looking in the first row that's returned. You need to call mysql_fetch_array in a loop to get each row. Also, you shouldn't use in_array(), since the article ID might appear in some other column (what if you're checking for article #3 and user #3?).
But if you just want to see if the article was created by this user, you can use a different query:
SELECT * FROM articles WHERE creatorid = '$userid' AND articleid = '$articleid';
This should return either 0 or 1 row depending on whether the user created the article. You can then use mysql_num_rows() to test for this.
It appears you are accessing the array incorrectly. On top of that you are returning multiple articles if the creator posted more than one so your in_array() is totally invalid. Change the limit on your query to one record (LIMIT 0,1) and access the creator id by calling:
$result[0]->creatorid or $result['creatorid']
depending on how your resource is queried

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