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!
Related
I am taking a users input and storing it in a database, however I want to be able to update the records if a user adds more information. So I want to search the database find the server with the same name and update the the last downtime and the number of downtimes.
$connect = mysqli_connect("localhost", "Username", "Password","Test_downtime");
if (!$connect)
{
die("Connection failed: " . mysqli_connect_error());
}else
{
echo "Connected successfully\n";
}
$servername = $_GET["server_name"];
$downtime = $_GET["downtime"];
$time_now = time();
$result = mysqli_query($connect, "SELECT COUNT(*) FROM `Test_downtime`.`Downtime` WHERE `Server_Name` = '$servername'");
$row = mysqli_fetch_array($result);
// If no downtime have been reported before
if ($row[0] == 0){
$sql = mysqli_query($connect, "INSERT INTO `Test_downtime`.`Downtime` (ID, Server_name, First_downtime, Last_downtime, Num_of_downtime,Total_downtime) VALUES (NULL, '$servername', '$time_now','$time_now',1,'$downtime'); ");
if ($sql==true) {
echo $servername . " has has its first downtime recorded\n";
}
}
//If users is already in the database
else{
$numdowntime = ($row["Num_of_downtime"] + 1);
$id = ($row["ID"]);
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
if ($sqlupdate == TRUE) {
echo "Oh No! " . $servername . " has had ". $numdowntime ." of downtimes" ;
}
}
?>
The program works fine if the server is not already in the database, the problems arise if the server is already in the database. I get the message saying it has been updated yet nothing happens to the database. How do i make it so it search and updates the records for the searched item.
So nothing append since you do not execute the sql statement ^^
Take a look here :
$sqlupdate = "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'";
You need to use :
$sql = mysqli_query($connect, $sqlupdate);
Just after it in order to execute it.
Or at least change it to
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
Btw there is other problem but here is the main one [check out the other answer in order to found another one ]
you are fetching the result as indexed array
mysqli_fetch_array($result);
and here you are accessing results as associative array
$numdowntime = ($row["Num_of_downtime"] + 1);
change your query to
mysqli_fetch_assoc($result);
use
mysqli_num_rows($result);
to checking if you have any data
change
if ($row[0] == 0){}
to
if(mysqli_num_rows($result) ==0){}
A good approach for increasing a count in a column is using SQL to increase that.
$sqlupdate = mysqli_query($connect, "UPDATE `Test_downtime`.`Downtime` SET `Num_of_downtime` = (`Num_of_downtime` + 1), `Last_downtime` = now() WHERE `Server_Name` = '$servername'" );
This way you can skip your $numdowntime calculation, and the result is more accurate.
In your current setup, two users may fire the event at the same time, they both retrieve the same number from the database (ie. 9), both increasing it with one (ie. 10), and writing the same number in the database.
Making your count one short of the actual count.
SQL takes care of this for you by locking rows, and you are left with a more accurate result using less logic :)
You miss the mysqli_query() function, which actually queries the database.
$sqlupdate = mysqli_query("
UPDATE `Test_downtime`.`Downtime`
SET `Num_of_downtime` = $numdowntime, `Last_downtime` = now()
WHERE `Server_Name` = '$servername'"
);
The below script inputs data to a database this takes some information from a form then stores them in to the database. And I'm also using uplodify to upload a image file and store the file name in the database but my issue is this data processing script keeps updating the row ID one never jumps to the second line I tried every thing can some one help me with this or show me what I'm doing wrong.
Also this checks the ID and if it's not equal to 1 then does an insertion if it's equal then update it but this not happening.
The ID is auto incrementing.
My script
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM poiinfo ORDER BY ID DESC LIMIT 1");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
//$poiId = $_REQUEST['pID'];
if($row['ID'] != "1"){
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon'";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
I tried u r suggestions but it's still the same now my code for the update is looks like this.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE `ID`='".$row['ID']."'";
But still it keeps up dating the ID 1 not moving on to the next one.
Your update query is missing a WHERE clause. Try this:
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE ID = '".$row['ID']."'";
Also be beware of MySQL Injections: http://en.wikipedia.org/wiki/SQL_injection
To check why your update failed, you should call mysql_error in your last else clause :
} else {
echo mysql_error();
}
As for the first problem : if you never insert a new record (I don't see how that could happen, provided your code), you will never have a record whose ID is 2.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon'";
You need a where clause in this sql to specify a record to update. Currently it is updating all records.
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE `ID` = ".$row['id']";";
You will need to set an $id variable for this to work.
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)
I am creating a browser statistics script in PHP.
When PHP finds a match in a table how do I retrieve the row and pull all three fields of the table into separate variables.
My table rows are (browser, version, amount)
so I want to select everything from the TB were
browser = $browser and version = $version.
But when this happens how do I add one to the amount field and resubmit the row. Without altering anything else. Below is the code I have.
$browser_name= "MSIE";
$version = "7";
$query = ("SELECT * FROM $TB
WERE browser = '$browser_name' AND version = '$version'");
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count == 1)
{
$mysql = ("SELECT * FROM $TB
WERE browser = '$browser_name' AND version = '$version'");
//code to add 1 to amount would be here
}
else
{
//if browser is not detected insert fresh row.
$mysql = "INSERT INTO $TB (browser, version, amount)
VALUES ('$browser_name', '$version', 1)";
}
I have been looking around for answers for ages but they just tell me how to select information out of a DB as a whole.
update table set amount_field = amount_field + 1 where browser = '$browser_name' and version = '$version'
I don't understand why you make twice the same select.
$browser_name= "MSIE";
$version = "7";
$query = "SELECT * FROM $TB WHERE browser = '$browser_name' AND version = '$version'";
$result = mysql_query($query);
if($data = mysql_fetch_assoc($result))
{
print_r($data);
//use UPDATE from other answers if you need one here.
}
else
{
//if browser is not detected insert fresh row.
mysql_query("INSERT INTO $TB (browser, version, amount)
VALUES ('$browser_name', '$version', 1)");
}
Beware of SQL injections!
SELECT * FROM $TB WHERE browser
you have a mistake it must be WHERE instead of WERE.
You update query will be like this
UPDATE $TB SET ammount = 1 WHERE browser = $browser and version = $version
There are hundreds of issues with your query like sanitization etc. I suggest you read a good mySQL book to improve the queries. But to answer your question:
//code to add 1 to ammount would be here
mysql_query("update $TB set amount = amount + 1 where browser = '".mysql_real_escape_string($browser_name)."' and version = '".mysql_real_escape_string($version)."'");
First of all, you should connect to db using
$db = new mysqli('host','user','pass','dbname');
Then, your query isn't right. You have a sql syntax error.
SELECT * FROM table WHERE column = value
So, without prepare, your code should look like:
$tb = 'table_name'; // to avoid sql injections use addslashes() to your input
$browserName = addslashes('browser_name'); // like this
$version = '7';
$db = new mysqli('host','user','pass','dbname');
$result = $db->query("SELECT * FROM $tb WERE browser = '$browserName' AND version = '$version'");
// Than, you can fetch it.
while ($result->fetch as $row) {
echo $row['yourColumn']; // will display value of your row.
}
$db->query("INSERT INTO $tb (browser, version) VALUES ('$browser_name', '$version')";
}");
And, that's all. You can count your records using mysql count() method. Your code will work. I advice you, at first go to php.net and check the doc. There are many examples.
*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)