Trouble with simple hit counter in PHP [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm cobbling together a very simple PHP script, but I can't get it to work. I'm connecting to the SQL database, but it's not retrieving the value I want. I just have a single entry in a single table in a single database. I want to retrieve that value, then add one to it.
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$dbtable = 'counter';
//------ DATABASE CONNECTION --------//
mysql_connect($dbhost,$dbuser,$dbpass)
or die ("Unable to connect to database");
mysql_select_db($dbname)
or die ("Unable to select database");
$test = "SELECT FIRST('count') FROM $dbtable";
?>
This button has been clicked <?php echo $test; ?> times.
EDIT: Found a solution with the aid of angelo
<?php
//parameters to set
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$dbtable = 'counter';
$dbcolumn = 'count';
//end of list of parameters to set
$connect = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$connect){die("Connection error");}
$test = mysqli_query($connect,"SELECT ".$dbcolumn." FROM ".$dbtable);
$assoc = mysqli_fetch_assoc($test);
$num = $assoc[$dbcolumn];
?>
This button has been clicked <?php echo $num; ?> times.
<?php
$plus = $num+1;
//mysqli_query($connect,"INSERT INTO ".$dbtable."('".$dbcolumn."') VALUES ('".$plus."')");
mysqli_query($connect,"DELETE FROM counter WHERE count = $num");
mysqli_query($connect,"INSERT INTO counter (count) VALUES ($plus)");
?>

Why your code is not working
You're not launching your query
Warning
You're using mysql_ functions, which are deprecated. You should use mysqli_ instead.
Solution
Use this code:
<?php
//parameters to set
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'test';
$dbtable = 'counter';
$dbcolumn = 'col';
//end of list of parameters to set
$connect = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$connect){die("Connection error");}
$test = mysqli_query($connect,"SELECT ".$dbcolumn." FROM ".$dbtable);
$assoc = mysqli_fetch_assoc($test);
$num = $assoc[$dbcolumn];
?>
This button has been clicked <?php echo $num; ?> times.
Please note that this code only shows the number of clicks.
To add one to this value, append the following code to the previous one:
<?php
$plus = $num+1;
$query = "UPDATE ".$dbtable." SET ".$dbcolumn."='".$plus."'";
mysqli_query($connect,$query);
?>

Related

could not connect to db [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 5 years ago.
Im haveing a problem with this code:
<?php
include 'connect.php';
$SQL = "INSERT into users(username, password, email,)
VALUES ('dado','123','neki#gmail.com',)";
mysql_query($SQL) or die("could not register");
?>
My connect.php looks like this:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'igra';
?>
When I try to exectue it, Im getting error. Tryed testing connection with
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'igra';
$connect = mysql_connect($dbhost, $dbuser, $dbpass)
or die("Unable to connect to dbhost");
mysql_select_db($dbname)
or die("Could not connect to db");
$test_query = "SHOW TABLES FROM $dbname";
$result = mysql_query($test_query);
$tblCnt = 0;
while($tbl = mysql_fetch_array($result)) {
$tblCnt++;
#echo $tbl[0]."<br />\n";
}
if (!$tblCnt){
echo "There are no tables<br />\n";
} else {
echo "There are $tblCnt tables<br />\n";
}
?>
and it return msg: There are 4 tables. Which means connect.php is properly set. Now I tryed to run code into MySQL Admin program itself with "INSERT into" query, and it worked. So, everything seems to work fine separatly, but when put together, it wont work.
Can somebody point me to misstake Im makeing please?

Database selection (PHP)

How do I choose a tbl_uploads table in the database?
PHPMYADMÄ°N IMG
<?php
$dbhost = "";
$dbuser = "";
$dbpass = "";
$dbname = "";
mysql_connect($dbhost,$dbuser,$dbpass) or die('cannot connect to the server');
mysql_select_db($dbname) or die('database selection problem');
?>
You don't need to choose any table just fire the Query on the database in which the table exists, and you're done. For example,
<?php
$dbhost = "";
$dbuser = "";
$dbpass = "";
$dbname = "";
mysql_connect($dbhost,$dbuser,$dbpass) or die('cannot connect to the server');
mysql_select_db($dbname) or die('database selection problem');
$query = "SELECT * FROM tbl_uploads;"
//executing the query and printing it's results
$results= mysql_query($query);
print_r($results);
?>
This will print the results of query in the variable $results.
Note :
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_query()
PDO::query()
First, connect to your database (keinotis_iletisim). For example:
$dbhost = "localhost"; // or any other address
$dbuser = ""; // the user you created for the database in phpmyadmin
$dbpass = ""; // the password you created for the database in phpmyadmin
$dbname = "keinotis_iletisim";
Then, in a query you can mention a table, for example:
SELECT * FROM tbl_uploads;
Also see this link on W3Schools.
You can select your table using sql statement like this
$sql = "SELECT * FROM MyGuests";
$result = mysql_query($conn, $sql);
Now you can fetch the all records by using
while($row=mysql_fetch_array($result))
{
echo $row['column_name'];
}
This one will work for you
<?php
//the connction
$hostname_localhost = "localhost";
$database_localhost = "keinotis_iletisim";
$username_localhost = "root";
$password_localhost = "";
$localhost = mysql_pconnect($hostname_localhost, $username_localhost, $password_localhost) or trigger_error(mysql_error(),E_USER_ERROR);
?>
<?php
mysql_select_db($database_localhost, $localhost);
$query_record = "SELECT * FROM tbl_uploads";
$record = mysql_query($query_record, $localhost) or die(mysql_error());
$row_record = mysql_fetch_assoc($record);
$totalRows_record = mysql_num_rows($record);
//echo $row_record['tbl_uploads_table_colum'];
?>
<!--And if you want to display the list-->
<?php do { ?>
<?php echo $row_record['tbl_uploads_table_colum']; ?>
<?php } while ($row_record = mysql_fetch_assoc($record)); ?>

mysqli_query not working when called from inside a function [duplicate]

This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 7 years ago.
Here is my code:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'root';
$db_database = 'drmahima_com';
$link = mysqli_connect($db_host,$db_user,$db_pass,$db_database) or die('Unable to establish a DB connection');
mysqli_query($link, "SET names UTF8");
function temp() {
$patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
echo $patient['name'];
}
temp();
?>
When I run this, the query doesn't seem to execute and nothing shows up on the page. However, if I remove the function and just change the code to this:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'root';
$db_database = 'drmahima_com';
$link = mysqli_connect($db_host,$db_user,$db_pass,$db_database) or die('Unable to establish a DB connection');
mysqli_query($link, "SET names UTF8");
// function temp() {
$patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
echo $patient['name'];
// }
// temp();
?>
It works, and the patient's name is displayed.
What is going on here?
Pass the $link to function as a parameter. Try this:
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'root';
$db_database = 'drmahima_com';
$link = mysqli_connect($db_host,$db_user,$db_pass,$db_database) or die('Unable to establish a DB connection');
mysqli_query($link, "SET names UTF8");
function temp($link) {
$patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
echo $patient['name'];
}
temp($link);
?>
Pass $link to the function. It is not working because of the scope of that variable. Try with -
function temp($link) {
$patient = mysqli_fetch_assoc(mysqli_query($link, "SELECT name,dob FROM patients WHERE id='69'"));
echo $patient['name'];
}
temp($link);

New $_SESSION variable not created after query?

I'm trying to build a login process where, by using $_SESSION variables, the login credentials of the user are stored and used to show their relevant data from the database on screen (i.e. they will only see the school data that they work for).
<?php
session_start();
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
{
$host = "xxx";
$username = "xxx";
$password = "xxx";
$database_name = "xxx";
$table_name = "xxx";
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
$query = "SELECT Class FROM $table_name WHERE Initials = '".
$_SESSION['Initials']."' AND staff LIKE '%".$_SESSION['Surname']."'";
$result = mysql_query($query);
$class = mysql_fetch_array($result);
$count = mysql_num_rows($result);
if($count === NULL)
{
echo "ERROR";
}
else
{
$_SESSION['Class'] = $result;
echo "Class added to sessions";
}
}
?>
My initial problem where the query couldn't recognize the session variables was easily solved by adding the correct brackets for the if-statement. My next problem that has arisen here is that even though the query should be successfull (I don't receive an error message saying 'ERROR' when the $count is either FALSE or NULL) it's not creating the result array into a new session, because when I print the session array on a new page it's still only carrying over the 'Initials' and 'Surname' sessions.
What do I need to change to my query, or post-query process in order for that array (because it's bound to throw up multiple results) to be made into a new session?
Many thanks for the answers to my initial problem!
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
// code
}
u need { } brackets
if(!isset($_SESSION['Initials'], $_SESSION['Surname']))
$host = "xxxxx"; $username = "xxxxx"; $password = "xxxxx";
is
if(!isset($_SESSION['Initials'], $_SESSION['Surname'])) {
$host = "xxxxx";
}
$username = "xxxxx";
$password = "xxxxx";
I've found the answer - it turned out that I wasn't treating one of the session variables as a proper array and thus wouldn't load properly. I've added my script below so that people with similar problems in the future can use it as a reference point:
<?php
session_start();
// Server Details //
$host = "---";
$username = "---";
$password = "---";
$database_name = "---";
$table_name = "---";
// Connect Command //
mysql_connect($host, $username, $password) OR die("Can't
connect");
mysql_select_db($database_name) OR die("Can't connect to
Database");
// Query to call up the unique school name //
$query_school = mysql_query("SELECT DISTINCT School FROM $table_name
WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_school = mysql_result($query_school, 0);
// Query to call up the unique centre no //
$query_centreno = mysql_query("SELECT DISTINCT CentreNo FROM
$table_name WHERE Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$result_centreno = mysql_result($query_centreno, 0);
// The newly created sessions for school info //
$_SESSION['---'] = $result_school;
$_SESSION['---'] = $result_centreno;
// Query to call up the array of classes //
$query_class = mysql_query("SELECT Class FROM $table_name WHERE
Initials = '".$_SESSION['---']."'
AND staff LIKE '%".$_SESSION['---']."'") or die( mysql_error());
$query_class__array = array();
while($row = mysql_fetch_assoc($query_class))
$query_class_array[] = $row;
$_SESSION['---'] = $query_class_array;
?>

Comparing database stringvalue with new stringvalue

Here is what I'm trying to do: When user adds a contact to his list, the number of this contact gets run by with the numbers in the database and it gives feedback if the user is already in the database or not. Right now I always get back "User is in database" even though he isn't. Then again I'm not that well acquainted with php. I changed the code a bit again, now it doesn't work at all, because it doesn't like the part
$number = ($_GET["number"] from $DB_Table);
Full code
<?php
$DB_HostName = "localhost";
$DB_Name = "db";
$DB_User = "user";
$DB_Pass = "pw";
$DB_Table = "contacts";
$number = ($_GET["number"] from $DB_Table);
$fnumber = ($_GET["fnumber"]);
if ($number == $fnumber) {
echo "This user is already in database";
} else {
echo "This user isn't in the database";
}
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
mysql_close($con);
?>
I don't actually see you executing the database query. You could do something like this:
<?php
$DB_HostName = "localhost";
$DB_Name = "db";
$DB_User = "user";
$DB_Pass = "pw";
$DB_Table = "contacts";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$fnumber = mysql_real_escape_string($_GET["fnumber"]);
$result = mysql_query("SELECT * FROM $DB_Table WHERE Something = '$fnumber'", $con);
if ($result) {
// Check the number of rows in the result set
if (mysql_num_rows($result) > 0) {
echo "This user is already in database";
}
else echo "This user isn't in the database";
}
mysql_close($con);
?>
This is not valid PHP code: $number = ($_GET["number"] from $DB_Table);
$_GET["number"] represents the value of the "number" parameter that you find in the url of your page.
Example: http://example.com/index.php?number=7 so $_GET["number"] is 7.
In your code, $DB_Table is a just a string ("contact") and "from" does not fit there using php syntax.
mysql_select_db($DB_Name,$con) or die(mysql_error());
is valid PHP but you are not doing anything with what you get from the database. I suggest you at least take a look at this tutorial php mysql select

Categories