I am having a problem with mysql. My php code is not working.
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
}
?>
I have tested putting some echo on my codes. Once i put the echo code on the while loop the echo doesnt work. Can anyone help me.
Try this :
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
$find_counts = mysql_query("SELECT * FROM user_count");
$current_count = 0;
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
}
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE 'visitor_counter' . 'user_count' SET
'counts'=$new_count");
Check if your SELECT query works by change the code:
mysql_query("SELECT * FROM user_count") or die(mysql_error());
Check if there is data in de table user_count and edit the query:
while($row = mysql_fetch_assoc($find_counts))
{
print_r($row); //to print the database row
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts=".$new_count); // no need to specify the database, you already did with mysql_select_db.
}
Dont need to specify DB, and quotes are wrong, change to:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count");
You also might want to specify a page:
$update_count = mysql_query("UPDATE user_count SET counts = $new_count WHERE page = '$this_page'");
what are you trying here ?
mysql_query("UPDATE 'visitor_counter' . 'user_count' SET 'counts'=$new_count");
whats the table name ?
i guess your tablename is user_count
or do you have more than one tablename you like to update ?!?!?
if tablenam eis user_count it should look like
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
so the total while would be
while($row = mysql_fetch_assoc($find_counts))
{
$current_count = $row['counts'];
$new_count = $current_count + 1;
$update_count = mysql_query("UPDATE user_count SET counts={$new_count}");
}
Important
Dont use
'tablename'
in your sql query... if you like to declair a tablename use
`tablename`
Use single query:
UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1;
then do your SELECT ... FROM
because passing variable into sql query for this kind of operations are not always safe
and here is Your code:
<?php
mysql_connect("localhost", "root", "root") or die("Unable to connect to the database");
mysql_select_db("visitor_counter") or die("Database is not created");
mysql_query("UPDATE `visitor_counter`.`user_count` SET `counts`=`counts`+1");
$counts = array();
$result = mysql_query("SELECT * FROM user_count");
while($data = mysql_fetch_assoc($result)) {
$counts[$data['id']] = $data['counts'];
}
?>
I'm really surprised to see everybody here posts code using the old and deprecated mysql functions (although some of them stated this is wrong). I would like to advice you AGAINST using mysql functions - they are deprecated as of version 5.5. You should use either mysqli or PDO instead. In my opinion, you should be using PDO as it provides support for almost all databases and you could use prepared statements.
Now to your code - I'm not quite sure why would use a cycle to count all of the records in the counts column. A much better way to do this is by using atomic increment - it will also guarantee your counter is properly incremented in case two queries are trying to increment the value simultaneously. Although you haven't posted your table structure, I believe something like this should do the work:
<?php
// Database connection settings
$db_host = '127.0.0.1';
$db_name = 'visitor_counter';
$db_user = 'root';
$db_pass = 'root';
// Try to connect to the database
try {
$dsn = 'mysql:host='.$db_host.';dbname='.$db_name;
$db = new PDO($dsn, $db_user, $db_pass);
} catch ( PDOException $e ){
// Do something if connection could not be established
throw new ErrorException("Could not connect to database!",0,1,__FILE__,__LINE__,$e);
}
// Find counts
// Assuming you have a user_id column in your `user_count` table.
$user_id = 1;
// Update counter
$update = $db->prepare('UPDATE user_count SET counter=(counter+1) WHERE user_id = :user_id');
$update->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$update->execute();
?>
P.S. In this code I'm assuming you're saving the visitor counter in the user_count.counter column and whenever somebody visits that user, the counter column is incremented for that specific user, rather than updating the counter for all users (as your code suggests).
Related
I have this code:
<?php
//MYSQL
$dbserver="..."; //adresa MySQL
$dblogin="..."; //jméno uživatele MySQL
$dbheslo="..."; //heslo MySQL
$dbnazev="..."; //název databáze MySQL
$mysqli = new mysqli($dbserver, $dblogin, $dbheslo, $dbnazev);
if ($mysqli->connect_error) {
die('Nepodařilo se připojit k MySQL serveru (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$mysqli->query("SET NAMES 'utf8'"); // nastavíme kódování MySQL
while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){
$tempid = $row['tempid'];
$jmeno = $row['jmeno'];
$prijmeni = $row['prijmeni'];
$email = $row['email'];
$bydliste = $row['bydliste'];
$souhlas = "on";
$aktuality = "on";
$timestamp = time();
$hash = md5("77c0a83besxxxcg1a190ab90d".time().$tempid.rand(10000000, 99999999));
$poznamky = "import19052018";
$vloz ="INSERT into `potvrzenotest` set jmeno='".$jmeno."', prijmeni='".$prijmeni."', bydliste='".$bydliste."', email='".$email."', souhlas='".$souhlas."', aktuality='".$aktuality."', timestamp='".$timestamp."', hash='".$hash."', poznamky='".$poznamky."';";
$result=$mysqli->query($vloz);
$cas = date('H:i');
echo '['.$cas.'] ID '.$tempid.' imported.', PHP_EOL;
}
mysqli_close($mysqli); .
?>
I have one table with some data and I have to copy it to another table with some additional data (like hash etc.).
When I run the code above, I got this:
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
[17:17] ID 1 imported.
So, only 1 row is being copied.
Could you please help me, where is the problem?
while($row = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL")->fetch_assoc()){ ... }
This loop will never end. And it will fetch the first row again and again.
You should execute the query outside the loop:
$selectResult = $mysqli->query("SELECT * FROM `importovat_fyz` WHERE `tempid` IS NOT NULL");
while ($row = $selectResult->fetch_assoc()) { ... }
As a side note: Consider to use a prepared statement for your INSERT statement in the loop. This will prevent SQL syntax errors if some of the values may contail special characters like '. If you run them in one transaction, you might even improve the performance.
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'"
);
In the following code I'm attempting to connect to my database, pull the maximum ID from my table and then generate a random number using the the rand() function. The code successfully connects me to the the database but when I try to call for the maximum ID it won't return a value.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) FROM 'table'";
$rannmr = rand(1, $amount);
// Close the mysql connection
mysqli_close($dbLink);
?>
Any help in resolving this would be appreciated.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
Firstly, you are using the wrong identifier for FROM 'table' being single quotes.
If table is indeed the table's name, wrap it in backticks, your question shows file.
$amount = "SELECT MAX(id) FROM `table`";
Either way, you cannot use quotes around a table name. It appears you are using file as your table name.
So if table is only an example and it is called file let's just say, you would do:
$amount = "SELECT MAX(id) FROM `file`";
or
$amount = "SELECT MAX(id) FROM file";
Then, you also need to query, using mysqli_query() which you are not doing.
$amount = mysqli_query($dbLink,"SELECT MAX(id) FROM `file`");
Or Object oriented style:
$amount = $dbLink->query("SELECT MAX(id) FROM `file`");
if($amount){
echo "Success!";
}else{
die('Error : ('. $dbLink->errno .') '. $dbLink->error);
}
See example #1 from http://php.net/manual/en/mysqli.query.php
Use or die(mysqli_error($dbLink)) to mysqli_query() which would have signaled the error.
http://php.net/manual/en/mysqli.error.php
Edit:
Try the following. You may need to modify $row[0] and rand(0,$count) as 1 depending on the column number.
$result = $dbLink->query("SELECT MAX(id) FROM mytable")
while ($row=$result->fetch_row()) { $count = $row[0]; }
$random = rand(0,$count);
echo $random;
use this:
$amount = "SELECT MAX(id) FROM table";
You forgot to execute the MySQL-query:
$amount = $dbLink->query("SELECT MAX(id) FROM table")->fetch_assoc();
$rannmr = rand(1, $amount[0]);
You never executed the query, you need more logic
if ($result = mysqli_query($dbLink, "SELECT MAX(id) as amount FROM `table`")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
if ($row = mysqli_fetch_assoc($result)) {
$amount = $row['amount'];
$rannmr = rand(1, $amount);
}else{
echo 'no row found';
}
}
mysqli_close($dbLink);
I didn't seem to see the line of code which actually does the query:
Try this: Using the object-oriented mysqli approach
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) as max_id FROM 'table'";
// Do the actual query :
$run_query = $dbLink->mysql->query($amount);
// Retrieve the values:
$result = $run_query->fetch_array();
// Do the rand function together with the retrieved value
$rannmr = rand(1, $result['max_id']);
// Now you can echo the variable:
echo $rannmr;
// Close the mysql connection
mysqli_close($dbLink);
?>
Thanks!!
sorry to bother you all but I'm really struggling with this one:
I connect to my database fine and then I try the following mysql statements:
$query1 = "select row1 from mydatabase where row2 = $Name ";
$answer1 = mysql_query($query1);
However, a few lines later when I try :
echo $answer1;
I'm given only nulls :(
Can anyone give me any suggestions please?
edit:
SQL logins:
mysql_connect("correct", "username", "password");
mysql_select_db("dbname") or die(mysql_error());
everything you did is right you have just to fetch the data like this:
$query1 = "select row1 from mydatabase where row2 = $Name ";
$answer1 = mysql_query($query1);
while($data= mysql_fetch_array($answer1)){
echo $data['row1'];
}
And this is a complet answer, i adjust it as you need ;)
<?php
//Connect to your database
$con=mysqli_connect("db_hostname","db_user","db_password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Value of the row to select
$row2 = 'some value';
//Make select query
$result = mysqli_query($con, "SELECT row1 FROM MyTable WHERE row2='$row2'");
//Fetch datas
while($row = mysqli_fetch_array($result))
{
echo $row['row1'];
echo "<br>";
}
//Close database
mysqli_close($con);
?>
Good Luck :)
Try using MySQLi_* instead MySQL_* functions and pass the connection variable to the function calls.
If this doesn't work then you might want to try some further debugging by enabling all error reporting and dumping the global scope.
<?php
error_reporting(E_ALL); // Show all errors & warnings
$conn = mysqli_connect("server", "username", "password");
mysqli_select_db($conn, "dbname") or die(mysql_error());
$sql1 = "SELECT `row1` FROM `mydatabase` WHERE `row2` = '".$Name."';";
$query1 = mysqli_query($conn, $sql1);
$answer1 = mysqli_fetch_assoc($query1);
var_dump($GLOBALS); // Dumps all variables in the global scope
?>
add this after $answer1= mysql_query($query1);
while ($row = mysql_fetch_assoc($answer1)) {
// echo data
echo $row['row1'];
}
Built this, and executed it, but the database in phpmyadmin has no changes... what am I missing?
Active is obviously a column name in each table... there are 107 tables I need to flip.
Thanks.
<?php
mysql_connect("localhost", "root", "789feRNSHB")or die("cannot connect to server");
mysql_select_db("core")or die("cannot select db");
$sql = "SHOW TABLES FROM core";
$result = mysql_query($sql);
$arrayCount = 0;
while($row = mysql_fetch_row($result)) {
$tableNames[$arrayCount] = $row[0];
$arrayCount++; //only do this to make sure it starts at index 0
}
//print_r($tableNames);
for($i=0;$i<sizeof($tableNames);$i++){
$table= $tableNames[$i];
echo $query = "UPDATE ".$table." SET Active=1 where Active=-1";
echo'>>'.mysql_query($query).'<br>';
}
?>
Explicitely call the mysql_error() function to see what happens. Example in http://ca2.php.net/manual/en/function.mysql-error.php.