I'd like to check if a value is already in the table.
The structure of my table is this:
ApplicantId = INT
EventId = INT
StudentId = INT
No need to use unique because these table has dependencies.
Below is what I have tried so far:
include('../connectdb.php');
$ScholarPointId = $_GET["ScholarPointId"];
$Point = $_GET["Point"];
$ScholarId = $_GET["ScholarId"];
$EventId = $_GET["EventId"];
$verifysql = mysql_query("SELECT EventId FROM scholar_attended_events WHERE ScholarId ='$ScholarId' ");
#$resultVerify = mysql_fetch_assoc($verifysql);
$num_rows = mysql_num_rows($verifysql);
if( $num_rows > 0 )
{
$script = "<script>
alert('The user has already attended this event!');
</script>";
header('updatescholarpoints.php');
exit();
}
else{
$result = mysql_query("UPDATE scholar_points
SET scholar_points.Points =
scholar_points.Points + $Point
WHERE scholar_points.ScholarPointId = '$ScholarPointId' ") or die(mysql_error());
mysql_query("INSERT INTO scholar_attended_events (EventId , ScholarId) VALUES( '$EventId' , '$ScholarId' ) ")
or die(mysql_error());
}
?>
What I want is to check if the EventId is already in taken by the Student = StudentId. If so, then system will prompt an alert box. Otherwise, Update and Insert into respective table. How can I do this? It seems I miss something in here. If you could help, I really appreciate it.
just missing an = ?
$verifysql = mysql_query("SELECT EventId FROM scholar_attended_events WHERE ScholarId =$ScholarId ");
(and use PDO or mysqli, your code is really in a deprecated mode)
Related
I have a problem when trying to update table after checking row. Not sure if the "if" statement is wrong, however I'm not quite sure, why the UPDATE sql is returning this error. I wouldn't be suprised if INSERT did that.
Here's part of code:
$sql = "SELECT user_id FROM players WHERE user_id = '$id'";
$result = $connect->query($sql);
if($result->num_rows > 0)
{
$sql = "UPDATE players SET user_id = '$Player->user_id', display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
if($connect->query($sql) === TRUE)
{
echo 'Table has been successfully updated.';
}else{
echo 'There has been a problem with updating the "players" table. <br>Error: '.$connect->error;
}
}else{
$sql = "INSERT INTO players(user_id, display_name, attackPower, defensePower) VALUES('$Player->user_id', '$Player->display_name', '$Player->attackPower', '$Player->defensePower')";
if($connect->query($sql) === TRUE)
{
echo'Table has been successfully migrated.';
}else{
echo'Table migration has failed.';
}
}
$connect->close();
INSERTing is working just fine. I would appreciate any advice. Thanks.
Your update query should look like:
$sql = "UPDATE `players` SET `display_name` = '{$Player->display_name}',
`attackPower` = '{$Player->attackPower}', `defensePower` = '{$Player->defensePower'}
WHERE `user_id` = '{$Player->user_id}'";
It cause an error because Identity columns are not updateable.
You can update every columns except them:
$sql = "UPDATE players SET display_name = '$Player->display_name', attackPower = '$Player->attackPower]', defensePower = '$Player->defensePower'";
As #aynber and #Julqas said, problem was my sql was missing WHERE condition. Thanks for help.
I am writing a Php 5 and Mysql 5 page counter script. When a student having id as 'visitorid' visits a page having id 'pageid' (both int(11)) the page counter tries to log the visit in 'visitors' database. But counter is not updating in mysql db, instead the visit_counter int(4) turns to 0.Whats wrong with my code? visitdate is datetime.
<?php
$pageid = 101;
$visitorid = 234;
$sql = "SELECT * FROM visitors
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("Error 1.<br>".mysql_error());
$data = mysql_fetch_array($temp);
// visit_counter is a field in table
if(($data['visit_counter']) != NULL){
echo "Entery exists <br>";
// Tried below version also
$visit = " SET visit_counter = visit_counter+1";
//$visit_counter = $data['visit_counter'];
//$visit = " SET visit_counter = ".$visit_counter++ ;
// Valid SQL
// UPDATE `visitors`
// SET visit_counter = visit_counter+1
// WHERE pageid = 101 and visitorid=234
// This manual sql query updates in phpmyadmin
$sql = "UPDATE visitors ".$visit."
AND visitdate = NOW()
WHERE pageid = ".$pageid."
AND visitorid = ".$visitorid;
$temp = mysql_query($sql) or die("ERROR 3.<br>".mysql_error());
//No error is displayed on above query.
} else {
//first entry
$visit_count = "1";
$sql = "INSERT INTO visitors
(`pageid`,`visitorid`, `visitdate`, `visit_counter`)
VALUES ('".$pageid."','".$visitorid."', NOW(), '".$visit_count."')";
$temp = mysql_query($sql);
//first entry is inserted successfully
//and visit_counter shows 1 as entry.
}
?>
Can anyone tell me whats wrong with this code?
Oh! I got answer by myself. Sometimes just little errors make us go crazy..
I made a mistake in udate query.. rather than using and I should have user a comma instead. .. working well now!
Basically, I have been having some trouble with sending a request to a MySQL server and receiving the data back and checking if a user is an Admin or just a User.
Admin = 1
User = 0
<?php
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`";
$checkAdmin = $checkAdminQuery
mysqli_query = $checkAdmin;
if ($checkAdmin == 1) {
echo '<h1>Working!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
Sorry that this may not be as much info needed, I am currently new to Stack Overflow.
Firstly, your SQL query is wrong
SELECT * FROM `users` WHERE `admin`
It's missing the rest of the WHERE clause
SELECT * FROM `users` WHERE `admin` = 1
Then you're going to need fetch the result from the query results. You're not even running the query
$resultSet = mysqli_query($checkAdminQuery)
Then from there, you'll want to extract the value.
while($row = mysqli_fetch_assoc($resultSet))
{
//do stuff
}
These are the initial problems I see, I'll continue to analyze and find more if needed.
See the documentation here
http://php.net/manual/en/book.mysqli.php
You need to have something like user id if you want to check someone in database. For example if you have user id stored in session
<?php
// 1. start session
session_start();
// 2. connect to db
$link = mysqli_connect('host', 'user', 'pass', 'database');
// 3. get user
$checkAdminQuery = mysqli_query($link, "SELECT * FROM `users` WHERE `id_user` = " . $_SESSION['id_user'] );
// 4. fetch from result
$result = mysqli_fetch_assoc($checkAdminQuery);
// 5. if column in database is called admin test it like this
if ($result['admin'] == 1) {
echo '<h1>Is admin!</h1>';
}else {
echo '<h1>Not working!</h1>';
}
?>
// get all admin users (assumes database already connected)
$rtn = array();
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`=1";
$result = mysqli_query($dbcon,$checkAdminQuery) or die(mysqli_error($dbconn));
while($row = mysqli_fetch_array($result)){
$rtn[] = $row;
}
$checkAdminQuery = "SELECT * FROM `users` WHERE `admin`"; !!!!
where what ? you need to specify where job = 'admin' or where name ='admin'
you need to specify the column name where you are adding the admin string
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
I have this field on my database
email, addition so what i want is that WHERE email='$email' it will look that the data user had for addition. now for addition field we have 100,100,1000
how can i compute this with the echo 1200
my code is NOTE this is just a sample scriptcode i can't copy and paste my code here because it was long. so if you find typo error ignore it.
$sql = mysql_query( "SELECT * FROM user WHERE email = '$email' ") or die(mysql_error());
while ( $row = mysql_fetch_array($sql) ){
echo $row[addition] ++;
}
yes i know its not correct format. what should i change? do i need to use for or foreach? in order to add those computation?
tghanks
with correct (normalized) data structure you can do:
SELECT SUM(addition) AS total FROM users WHERE email = '$email'
if you store it as csv in a column as Ignas says in his commentes,
you can either fix your database structure or use php:
$sum = array_sum(explode(',', $row['addition']));
Somthing like?
$sql = mysql_query( "SELECT * FROM user WHERE email = '$email' ") or die(mysql_error());
while ( $row = mysql_fetch_array($sql) ) {
$iAdditionSum = 0;
$aAddition = explode(',', $row['addition']);
foreach($aAddition as (int) $iAddition) {
$iAdditionSum += $iAddition;
}
echo $iAdditionSum;
}