So I learn PHP, and I want to try to build something like a small monetized url shortener, just for fun! So every time somebody clicks on a users link, one click should be added in the MySQL table (for the user). I tried a lot of scripts but they all don't work.
<html lang="en-US">
<?php
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_query("UPDATE users SET 'hits' = 'hits'+1 WHERE id = 1");
?>
And after then display the clicks in the users dashboard via $row['']... but it doesn't count the clicks when I onload the page... the number in the mysql database does'nt change... what am I doing wrong. Alsom do you have and more professional idea how to do that, cause I know that this isn't a good alternative... I also have something like that , but it doesnt work too...
$user_ip=$_SERVER['REMOTE_ADDR'];
$check_ip = mysqli_query("select userip from pageview where page='1' and userip='$user_ip'");
if(mysqli_num_rows($check_ip)>=1)
{
}
else
{
mysqli_query("insert into pageview values('1','1','$user_ip')");
mysqli_query("update users set 'hits' = 'hits'+1 where id=1 ");
}
If you're used to mysql_query, you need to do this differently, a connection handle is required, no longer implicit. The best way to avoid slipping up on this is to use the object-oriented calling method:
$conn->query(...);
This approach is often substantially less verbose.
Related
I have a search box in the navigation bar of my web application that appears on every web page. I have a query that is supposed to pull results from my database based on the text the user enters in the search box but at the moment it doesn't show any results.
My web application is essentially a post it board for events so I want a user to be able to search for an event and then have that event displayed in either a table or to take it to the page of the event itself whichever is easier. I am using Netbeans as my IDE and my database is a MariaDB in XAMPP. My web application is just locally hosted for now. I currently have a query that should search the database but I think the output of the query or the result is wrong. I'm not great at PHP but just need to do this as it is in every page of the web application.
The code of the search bar on every page:
<form action="search.php" method="post">
<input type="text" name="search" placeholder="Search for an event..">
<input type="submit" value="Search">
</form>
Then the search.php file looks like this:
<?php
$search = filter_input(INPUT_POST, 'search');
$companyname = filter_input(INPUT_POST, 'companyname');
$eventname = filter_input(INPUT_POST, 'eventname');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "fyp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SELECT eventname FROM event WHERE eventname LIKE '%$search%'";
if ($conn->query($sql) === TRUE) {
echo "Result Found";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
At the moment, it just comes up saying "Connected successfullyError: SELECT eventname FROM event WHERE eventname LIKE '%Golf%'". I have an event called "SHARE Golf Classic" in the database so that's what I'm testing with currently. I would like to navigate to a page called Event.php and display the results in either a table or else fill labels or textboxes with the details of the event. The event table consists of eventid, eventname, eventtype, charityid, contactdetails, location and date.
Determining errors of objects (Mysqli) can be difficult, that's why you should use try-catch approach instead. Your code could look like this:
<?php
$search = filter_input(INPUT_POST, 'search');
$companyname = filter_input(INPUT_POST, 'companyname');
$eventname = filter_input(INPUT_POST, 'eventname');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "fyp";
try {
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT eventname FROM event WHERE eventname LIKE '%$search%'";
if (($result = $conn->query($sql)) === true) {
var_dump($result)
}
} catch (mysqli_sql_exception $e) {
var_dump($e)
} finally {
$conn->close();
}
Please bear in mind that using parameters from POST request in the query like this can be dangerous. I would suggest looking into a different MySQL client for PHP (PDO) and use prepared statements instead.
The code example above is also using finally, which was added in PHP 5.5, make sure your version is this or above (currently supported PHP versions are 7.2 and 7.3 - you should be always up to date).
Problem:
I want to get the MAX "SID" from my Database and add one. I handle the input via an Form that i submit through the HTTP Post Method. I get the current MAX "SID" from my database, then i put the value into an HTML input field and add one. For some reason this just works every other time. So the output i get is:
Try = 1
Try = 1
Try = 2
Try = 2
and so on. Would be nice if someone could point me in the right direction.
PHP get MAX(ID):
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT MAX(SID) FROM spieler";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$lastID = $row["MAX(SID)"];
}
}
mysqli_close($conn);
PHP insert in database:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?><br><?php
$sql = "INSERT INTO spieler VALUES ('$sid', '$name', '$verein',
'$position', '$einsaetze', '$startelf', '$tore',
'$torschuesse', '$eigentore', '$vorlagen', '$elfmeter',
'$verwandelt', '$gegentore', '$gelb',
'$rot', '$fouls', '$zweikampf', '$pass', '$note')";
if(mysqli_query($conn, $sql)){
echo "Success";
}else{
echo "Failed" . mysqli_error($conn);
}
mysqli_close($conn);
HTML & PHP Input Field:
<tr>
<td><input id="SID" name="SID" readonly value="<?php echo $lastID += 1;
?>"></td>
</tr>
Screenshot of the page:
The paragraph "Spieler ID:" is where I put the "SID" so that everytime the page loads the next free ID gets automatically loaded into the input field.
I want to get the MAX "SID" from my Database and add one
No. You don't. You really, really don't.
This is the XY Problem.
You can do it by running a system wide lock and a autonomous transaction. It would be a bit safer and a lot more efficient to maintain the last assigned value (or the next) as a state variable in a table rather than polling the assigned values. But this still ignores the fact that you going to great efforts to assign rules to what is a surrogate identifier and hence contains no meaningful data. It also massively limits the capacity and poses significant risks of both accidental and deliberate denial of service.
To further compound the error here, MySQL provides a mechanism to avoid all this pain out of the box using auto-increment ids.
While someone might argue that these are not portable, hence there may be merit in pursuing another solution, that clearly does not apply here, where your code has no other abstraction from the underlying DBMS.
I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.
The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly
Main script:
<?php
include connect.db;
//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";
//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
$stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
$stmt->bind_param("ssss", $type, $username, $password, $email);
$stmt->execute();
$stmt->close();
echo "User Registered";
}
else {
echo "Username, password or email are already used";
}
?>
Connection Script:
<?php
//Identifies the databases details.
//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";
/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
die("Connection failed: " . mysqli_connect_error());
}
?>
edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.
Try to see the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
I have a database named hrRecords and a table named employee in that table. It has a field named contract_end. In that field, I have the contract info of the employee specifically the duration of said contract (datetime).
What I want to achieve is to check that info to see when the contract is going to come to an end and if it is display a message saying so.
I am very new to php and I tried something but I am totally lost I was wondering if I could get some guidance of some sort thank you for your support:
<?php
$employee1= mysql_real_escape($_GET["employee1"]);
$DataBase = "hrRecords";
mysql_connect("server","username", "password") or die(mysql_error());
mysql_select_db($DataBase) or die(mysql_error());
$query = SELECT contract_end From hrRecords
// current date being compared
if(contract_end== date(Y-m-d) {
echo "something"
}
else {
echo " employe name , Your contract will expire in x amount of days "
}
/* This is the point where everything becomes fuzzy because im thinking there has to be some other way to do this for all the employees */
fist stop using mysql it has been depreciated
use either mysqli or pdo. I will show you how to do it with mysqli
<?php
$employee1= mysql_real_escape($_GET["employee1"]); // i am not sure why you are doing this since you are not using this any where
$DataBase = "hrRecords";
$ServerName = "server";
$UserName = "username";
$Password = "password";
$mysqli = new mysqli($ServerName, $UserName, $Password,$DataBase);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// since i don't know all of colum names i am making them up
$stmt= $mysqli->prepare("SELECT contract_end employe_name From hrRecords");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($contract_end, $employe_name)
while($stmt->fetch()) { // this will go thorough all of the records
// current date being compared
if($contract_end== date(Y-m-d) {
echo "something"
} else {
// you need some more code here to find x
echo " $employe name , Your contract will expire in x amount of days "
}
}
i don't know if this will help you at all. you did not have enough info for a better answer
I was wondering if anyone could shine a light on how to read from a database and pass it on to a sessions variable. I have tried with a product id and get but it did not work.
I'm looking for the basics on how to approach the issue.
I assume that you need to read from MySQL Database (for example).
First thing to do is reading PHP/MYSQL documentation.
http://www.w3schools.com/php/php_mysql_intro.asp
Second thing is to read about PHP Sessions.
http://www.w3schools.com/php/php_sessions.asp
And for example some code:
// Connect to MySQL Database and select all records from your_table
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = $conn->prepare("SELECT * FROM your_table");
$query->execute();
if($query == TRUE) {
// query success
}
To store information in $_SESSION variable you need to:
Call session_start(); before accessing this variable
$_SESSION['your_var'] = 'your_value';