I'm trying to make a click counter using PHP and mysql - php

<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$db_name = 'somedb';
$conn = mysqli_connect($hostname, $username, $password, $db_name);
if (isset($_POST['abc'])){
$date_today = date('Y-m-d');
$somecount=("INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', '') ON DUPLICATE KEY UPDATE somecount=somecount+1");
mysqli_query($conn, $somecount);
}
?>
<form method="post" action="some.php">
<input type="submit" name="abc">
</form>
I've tried this code. Someone please help me out to count the click made by the user on a button or submit input tag. Thanks in advance.

Just update this line:
From
$somecount=("INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', '') ON DUPLICATE KEY UPDATE somecount=somecount+1");
to
$somecount=("INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', '1') ON DUPLICATE KEY UPDATE somecount=somecount+1");
also, to make sure you are not redirecting to another page that the current page itself do the below code:
<form method="post" action="">
<input type="submit" name="abc">
</form>
doing so will make sure that you will submit to the same page.

I would suggest avoiding ON DUPLICATE KEY UPDATE and instead use a little bit different logic:
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$db_name = 'somedb';
$conn = mysqli_connect($hostname, $username, $password, $db_name);
if (isset($_POST['abc'])){
$date_today = date('Y-m-d');
$selectStatement = "SELECT somecount FROM sometable WHERE today = '".$date_today."'";
$selectResult = mysqli_query($conn, $selectStatemnt);
$finalStatement = "";
if($selectResult){
$finalStatement = "UPDATE sometable SET somecount = somecount + 1 WHERE today = '".$date_today."'";
}
else{
$finalStatement = "INSERT INTO sometable (today,somecount) VALUES ('".$date_today."', 1)";
}
mysqli_query($conn, $finalStatement);
}
?>
<form method="post" action="some.php">
<input type="submit" name="abc">
</form>
Here we first check if the row for today already exists in the table. If so simply increment it else create a row and set the count value to one.

Related

Insert into SQL database user input from HTML form

I am trying to insert into column "UserId" in my sql database, using php, text that the user inputs in the HTML form.
Below is a basic example to help me figure out what I am doing wrong.
HTML
<html>
<form action="index1.php" method ="post" name="trial">
<input type="text" name="testName" id="testId">
<br>
<input type="submit" value="Submit">
</form>
</html>
PHP
$servername = "localhost";
$username = "root";
$password = "xx";
$dbname = "wp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$UserId = $_POST['testName'];
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$testName')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Some notes:
I can connect to database and insert in the correct columns checkbox and radio values from the form
I cannot find a way to insert in the database the user text input from the form (UserProfile is the table and UserId the column).
Would using a javascript variable, like below one, help?
var testVar = document.getElementById("testId").value;
I know I am opening myself to hacking using the above code, I would like to improve it later on but I think I need to first figure out the basics (ie: how to get the user text input added to the database)
Than you in advance for any help!
you are storing the value in $UserId, not in $testName:
Change your SQL Query to
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$UserId')";
I think this will help.
BTW: Think about SQL-Injection! Look here: How can I prevent SQL injection in PHP?
Look here
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$testName')";
Change $testName to $UserId in sql statement because it's the name of your new variable in php:
$UserId = $_POST['testName'];
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$UserId')";
But I advice you to:
1- use PDO for any sql handling in php
2- use mysqli_real_escape_string to protect your code from threats.
make it like:
$UserId = mysqli_real_escape_string($con, $_POST['testName']);

Data not showing up on Wamp server database (using php)

I'm trying to INSERT data into a table in my database but I'm not able to. I'm using WAMP.
PHP Script:
$user = 'root';
$password = '';
$db = 'comments_schema';
$host = 'localhost:3306';
$mysqli = mysqli_connect('localhost', $user, $password, $db);
$sql = "INSERT INTO parent_comment(commentid, comment) VALUES ('". '
commentid'."', '". "hi" ."')";
$result = $mysqli->query($sql);
if($result > 0):
echo 'Successfully posted';
else:
echo 'Unable to post';
endif;
HTML Code:
</div>
<form action="database.php" method="post">
Comments: <input type="text" name="field_name" />
<input type="Submit" /></form>
However, the rows could not be inserted:
You can use backticks for SQL-related elements, ands single quotes around the values you want to insert.
$sql = "
INSERT INTO `parent_comment` (commentid, comment)
VALUES ('commentid', 'hi')
";
You can try this code:
'INSERT INTO parent_comment(commentid, comment) VALUES ('.commentid.', "hi")';

Use PHP variable to search through SQL database

I have a database called $addressdb. I want to search through a table on that database with a result the user inputted ($usersName). My mistake is probably really stupid. I am new with mySQL.
<?php
//IF THE LOGIN is submitted...
if ($_POST['Login']){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "addressdb";
$usersName = $_POST['users'];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";
$result = mysqli_query($conn, $sql);
...
My line of error is
$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";
More specifically the variable call.
Best approach is :
$sql = "SELECT userID, userName FROM users WHERE userName ='".mysqli_real_escape_string($conn, $usersName)."'";
Here it is not so applicable since you are passing the plain text. But when taking data from html page you should use this way.
Try something like this :
$sql = "SELECT userID, userName FROM users WHERE userName = '".$usersName."'";
You need to use quotes around your $userName.
$sql = "SELECT userID, userName FROM users WHERE userName = '$usersName'";
But to be clear, you should escape your user input at least with mysqli_real_escape_string($conn, $userName);

Non object error when using prepared statement

I have a table containing columns person and person_initials. When Submit is clicked I would like to insert the name in the input box into the person column in the table of names where the initial equals the initial defined. In this case only 1 row containing "I" in the person_initial column exists in the table.
Please see the code below. I'm sure there must be a basic syntax error in the prepared statement but I can't see it. Apologies for the ignorance.
index.php:
<html>
<body>
<form method="post">
Insert: <input type="text" name="q" value="Tim"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$test_name = $_POST['q'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "personnames";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$people = 'I';
$stmt = $conn->prepare("INSERT INTO names (person) VALUE=(?) where
person_initial=(?)");
$stmt->bind_param("ss",$test_name,$people);
$stmt->execute();
$stmt->close();
$conn->close();
}
?>
</body>
</html>
You seem to attempting an update, in which case the syntax would be:
$stmt = $conn->prepare("UPDATE names SET person=? where person_initial=?");
Your INSERT query is wrong. Use
$stmt = $conn->prepare("INSERT INTO names (person) VALUES(?)");
instead
$stmt = $conn->prepare("INSERT INTO names (person) VALUE=(?) where
person_initial=(?)");
If you want to update, then use update query like this
$stmt = $conn->prepare("UPDATE names SET person=? where person_initial=?");

How to get session variable from 2 different tables?

I am new in PHP. I use session first time. I have two tables in db. First table with name pacra_teams with column id and title. Second table is og_users with multiple column but i use team_title as foreign key as store id against team title.
Now i want to create a session and want to display team name from table pacra_teams and user name from table og_users.
I try following code but i failed.
<?php
// starts session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
// setting variable values during session
$_SESSION['og_users.username']=$username;
$_SESSION['pacra_teams.title']=$title;
?>
call these variables
<?php
session_start();
?>
<?php
print_r($_SESSION);
?>
Please help me how i can do this?
One Thing More. if i run seesion.php page it display undefine variable "title"
and if i run print code. It display username "root" but i dont have any user name root in my db
You already defined a query but didn't execute it.
// starts session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
$result = $conn->query($sql);
$row = $result->fetch_object();
// setting variable values during session
$_SESSION['og_users.username'] = $row->USER_NAME; // Change to correct column name in table og_users
$_SESSION['pacra_teams.title'] = $row->TITLE_COLUMN_NAME; // Change to correct column name in table pacra_teams
The result will be the same every time without a WHERE clause in your sql statement. It's only going to return the first row it finds. It looks like you're trying to set user information in a session variable so you can call the data throughout your application so here's a possible solution assuming you grab an ID for the user somewhere (IE web form).
This is a simple answer to explain a concept, not a tutorial.
<?php
//Setup your connection stuff here
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
//Get a user's name from a form
$userName = $_POST['username'];
// Perform your query
$db= new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
WHERE og_users.username = {$userName} LIMIT 1";
if(!$result = $db->query($sql)){
die('Error [' . $db->error . ']');
}
// Setting variable values during session
while($row = $result->fetch_assoc()) {
$_SESSION['ogUsername'] = $row['USERNAME']; // USERNAME is a placeholder for the example
$_SESSION['pacraTeamsTitle'] = $row['TITLE']; // Same here
}
It's not perfect, but hopefully it helps explain the concept and helps you complete your task.

Categories