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
Related
Hello I've a table named as "register" in which i've some records Lets says (10)
I want to first count that records and then save it into another table named as "not" i.e. Notification(Handler Name)
Here's the code which i'm using but unfortunately its not working..
Here's my config.php
<?php
$con = new mysqli('localhost','root','','admin');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
and here's abc.php
<?php
include('config.php');
$sql2 = "INSERT INTO not VALUES((SELECT count(*) as count FROM register))";
$result2 = mysqli_query($con, $sql2);
if($result2->num_rows>0)
{
while($rw1=$result2->fetch_array())
{
$value1 = $rw1['count'];
echo $value1;
}
}
?>
not is reserved word. So you should use like this:
$sql2 = "INSERT INTO `not` VALUES((SELECT count(*) as count FROM register))";
Basically i'm working on a project similar to Facebook Notification System
I've a Registration Form through which users are registered and all entries will be saved in a database named as "admin" with table name as "register"
Clear or not ?
Suppose I've 10 Users and I want to first show No. 10 as Notification Number at top bar as a popup tooltip
Just follow this example which i'm using
[http://demos.9lessons.info/notifications_css/index.php][1]
After that I want to Perform this thing that when someone opens the notification bubble, that 10 Number Goes out and in backend, i'm thinking that to store that ROW COUNT into another table and after Jquery click function, that table value goes to ZERO and when any new user is registered, then it increments the counter with match the previous value..
Sounds or not ??
change your table name as suggested by #phpPhil
plus try this query
$sql2="INSERT INTO not SELECT count(*) as count FROM register";
UPDATED
made your connection in this file.
$con = new mysqli('localhost','root','','admin');
$sql = "SELECT count(*) as count FROM register";
this query will return only one or zero rows so dont use while
$result = $con->quer($sql) or die($con->error);
if($result->num_rows>0)
{
$rw=$result->fetch_array(MYSQLI_ASSOC);
$value = $rw['count'];
echo $value; here to check what you get here
//preiously you had check if value is not empty. which is wrong because it will never empty it will either 0 or any other value
if($value!=0)
{
$jh ="update noti set noti='$value'";
$res=$con->query($jh) or die($con->error);
}
else
{
$ab ="insert into noti(noti) values('$value')";
$res1=$con->query($ab) or die($con->error);
}
}
I am a novice when it comes to PHP but I don't understand if my syntax is wrong in this statement, or how would I grab an int from my MySQL server.
I know that my server credentials are working fine. How would I fix this statement to give me a returned integer of the number of reviews in the userinfo table?
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$amountofreviews = $numberofpreviousreviews + 1;
$query2 = mysql_query("ALTER TABLE userinfo ADD `amountofreviews` VARCHAR(10000)") or die(mysql_error()); //Make another column in database for the new review
You need to fetch your results after you run your query. There are several ways to do this but using mysql_fetch_assoc() will work for you.
$numberofpreviousreviews = mysql_query("SELECT `number_of_reviews` FROM `userinfo`") or die(mysql_error()); //Check to see how many reviews user has previously created
$row = mysql_fetch_assoc($numberofpreviousreviews);
$amountofreviews = $row['number_of_reviews'] + 1;
FYI, you shouldn't be using mysql_* functions anymore. They are deprecated and going away. You should use mysqli or PDO.
Assume you have a table userinfo which has the following structure and data :
Scenario #1 :
If you want to retrieve the all number_of_reviews, then do like this,
$query = "SELECT `number_of_reviews` FROM `userinfo`";
$result = mysqli_query($db,$query);
while ($row = mysqli_fetch_assoc($result)) {
echo "Number of reviews : " . $row['number_of_reviews'] . "<br/>";
}
It will give you,
Number of reviews : 20
Number of reviews : 40
Since, the result has many rows, it will display like above.
Scenario #2:
If you want to retrieve only the specific number_of_reviews for some user id (which is unique). I take id as 1 as a example here. Then do like,
$query2 = "SELECT `number_of_reviews` FROM `userinfo` WHERE `id` = 1";
$result2 = mysqli_query($db,$query2);
while ($row2 = mysqli_fetch_assoc($result2)) {
echo $row2['number_of_reviews'] . "<br/>";
}
This will print,
20.
Because, number_of_reviews is 20 for id 1.
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
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
say I have a variable
$id = mt_rand();
how can I query the mysql database to see if the variable exists in the row id, if it does exist then change the variable $id, once the variable is unique to all other stored ids, then insert it into the database?
Thanks you guys.
$con = mysql_connect("<host>","<login>","<pass>");
if ($con) {
mysql_select_db('<schemata>', $con);
$found = false;
while (!$found) {
$idIamSearching = mt_rand();
$query = mysql_query("SELECT count(*) FROM <table> WHERE <idColumnName>='".$idIamSearching."'");
$result = mysql_fetch_row($query);
if ($result[0] > 0) {
mysql_query("INSERT INTO <table> (<column>) VALUES ('".$idIamSearching."')");
$found = true;
}
}
mysql_close($con);
}
Your description is hard to understand, so, this is something that could give you pointers...
'SELECT COUNT(*) as count from table where row_id="'.$variable.'" LIMIT 1'
make sure to escape the variable if it's user input or if it's going to have more than alphanumeric characters
then fetch the row and check if count is 1 or greater than 0
if one, then it exists and try again (in a loop)
although, auto increment on the id field would allow you to avoid this step
$bExists = 0;
while(!$bExists){
// Randomly generate id variable
$result = mysql_query("SELECT * FROM table WHERE id=$id");
if($result){
if(mysql_num_rows($result) > 0){
$bExists = 1;
} else {
// Insert into database
$bExists = 1;
}
}
1 Randomly generate id variable
2 Query database for it
2.1 Result? exit
2.2 No result? Insert