Data not showing up on Wamp server database (using php) - 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")';

Related

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

<?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.

Mysqli and PHP not sending data [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I'm building a recruiting website and need to save user data in my database but my form isn't sending anything to the database in phpmyadmin (using WAMP).
I checked the error logs for PHP, MySQL and Apache but don't see any errors. I also added "if/echo" blocks inside the $conn variables to test the connection, which returned true. Code below.
<!-- index.html-->
<form action="process.php" method="post">
<input type="text" name="first_name" placeholder="First Name" /><br/>
<input type="text" name="last_name" placeholder="Last Name" /><br/>
<button type="submit" name="submit"></button>
</form>
//database.php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "xxxx";
$dberror1 = "Could not connect to the database!";
$dberror2 = "Could not find selected table!";
// Connection to the database, Already tried this with echo statement and works
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die ($dberror1);
// Selecting the database to connect to
$select_db = mysqli_select_db($conn, 'mainbase') or die ($dberror2);
//process.php
<?php include 'database.php';
if(isset($_POST['submit'])) {
// Creating variables to store form values
$first_name= $_POST['first_name'];
$last_name=$_POST['last_name'];
//Executing the query
mysqli_query($conn, " INSERT INTO 'candidates'('first_name', 'last_name') //Values in 'candidates' table on phpmyadmin
VALUES ('$first_name','$last_name')");/*variables from above*/
}
You're using myqli incorrectly. But on top of that, use PDO to connect to your database instead. It's safer and easy to expand in the future. Here is an example of how to connect to your database with PDO.
<?php
$myUser = "XXXXXX";
$myPass = "XXXXXX";
try{
$dbPDO = new PDO('mysql:host=localhost;dbname=xxxxxxxx', $myUser, $myPass);
$dbPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection was successful";
} catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br />";
die();
}
?>
Simply change the Xs to your server's settings.
When you want to start a query simply you can do it like so:
$query = $dbPDO->prepare("SELECT * FROM Table_Name");
$query->execute();
Of course you'd want to pass variables to your queries so you can do that like this:
$query = $dbPDO->prepare("SELECT * FROM Table_Name WHERE ID = :id");
$query->bindParam(':id', $id);
$query->execute();
That keeps SQL injection off your worries. Just make sure to sanitize your variables before binding them to the query as well.
I figured I'd show how to insert your variables into your table with PDO.
$firstName = $_POST['first_name'];
$lastName = $_POST['last_name'];
$query = $dbPDO->prepare("INSERT INTO candidates first_name, last_name VALUES (:fname, :lname)");
$query->bindParam(':fname', $firstName);
$query->bindParam(':lname', $lastName);
$query->execute();
You could also make an array of both of your POST variables and pass that instead of binding each variable at a time.
$candidateName = array('$_POST['first_name']', '$_POST['last_name']');
$query = $dbPDO->prepare("INSERT INTO candidates first_name, last_name VALUES (?, ?)");
$query->execute($candidateName);
I hope that helps!
Happy coding!
The problem
Don't put table name and column names between apostrophes. That's what's causing your query to fail. Apostrophes are used to pass strings.
mysqli_query($conn, " INSERT INTO 'candidates'('first_name', 'last_name')
VALUES ('$first_name','$last_name')");
Should be
mysqli_query($conn, " INSERT INTO candidates(first_name, last_name)
VALUES ('$first_name','$last_name')");
Or
mysqli_query($conn, " INSERT INTO `candidates`(`first_name`, `last_name`)
VALUES ('$first_name','$last_name')");
if you like it better.
The error handling
In order to verify the problem you can echo the mysqli_error() function result whenever the query fails, it's a nice practice and would probably have helped you find a solution faster than asking it here.
$query= mysqli_query($conn, " INSERT INTO `candidates`(`first_name`, `last_name`)
VALUES ('$first_name','$last_name')");
if(!$query) //the query will return 0 if it fails
{
echo mysqli_error($conn);
}
The security issue
You're adding POST value directly into your query, which is dangerous.
On these lines:
$first_name= $_POST['first_name'];
$last_name=$_POST['last_name'];
You should be escaping user input.
This will escape any special characters that can cause issues in the mysql query.
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name = mysqli_real_escape_string($conn, $_POST['last_name']);

How to search a mysql data base via php script. (not working)

I can not return results with the php scritp that quires the database and echos results? All i get is fetched data successfully. Any help would be great and thanks.
<form action="#" method="get">
search: <input type="text" name="Id"><br>
<input type="submit" value="delete">
</form>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = '#####';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$search = $_GET['search'];
if($_GET){
$sql = 'SELECT Id, Employee_Name,
Employee_Email
FROM Blog
WHERE Id LIKE "%$sql%"';
mysql_select_db('test');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Tutorial ID :{$row['Id']} <br> ".
"Title: {$row['Employee_Name']} <br> ".
"Author: {$row['Employee_Email']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
}
mysql_close($conn);
?>
Double quotes don't work in SQL queries. This:
$sql = 'SELECT Id, Employee_Name,
Employee_Email
FROM Blog
WHERE Id LIKE "%$sql%"';
Should be this:
$sql = "SELECT Id, Employee_Name,
Employee_Email
FROM Blog
WHERE Id LIKE '%$search%'";
Also, it's time to stop using the deprecated mysql functions. Switch to mysqli for MySQL, and switch to PDO if you want to interface with MySQL and other types of databases (MSSQL, Oracle, etc.).
You have:
$search = $_GET['search'];
^^^^^^^---one variable name
Then have:
$sql = 'SELECT Id, Employee_Name,
Employee_Email
FROM Blog
WHERE Id LIKE "%$sql%"';
^^^^--- wrong variable name
e.g. using the wrong variable name, plus having a gaping wide-open SQL injection attack vulnerability.
You're using $sql within the string that DEFINES $sql, so that inner $sql is empty, and your query will be WHERE Id LIKE "%%", which will match everything.

Insert Into mysql using php

I am working with php and mysql for the first time. The goal is to have a table that store email addresses to form a mailing list for a newsletter. my table Emails has 2 columns ID (INT auto increment) and email (varchar, 255)
I can connect to the database but I cannot write to it. I think my problem is in the syntax of my INSERT INTO statement. I have seen many examples and they seem to use different syntax specifically around the values.
form code:
<form method="post" action="email.php" class="form-container">
<div class="form-title"><h2>Sign up for my newsletter!</h2></div>
<div class="form-title">Email Address</div>
<input class="form-field" required="required" placeholder="example#mail.com" type="text" name="newEmail" /><br />
<div class="submit-container">
<input class="submit-button" type="submit" value="Submit" /></div>
</form>
php code:
<?php
$dbHost = "localhost";
$dbUser = "input";
$dbPass = "input";
$dbName = "MailingList";
$conn= mysqli_connect ($dbHost, $dbUser, $dbPass, $dbName);
if(mysqli_connect_errno()) {
die("FAIL:". mysqli_connect_error() . "(" . mysqli_connect_errno() . ")");
}
$addEmail = "mysqli_real_escape_string($_POST['newEmail'])";
$query ="INSERT INTO Emails (email) VALUES ('$addEmail')"
mysqli_close($conn)
?>
You have missed to add the $conn i.e database link to the mysqli_real_escape_string and also, you have wrapped the mysqli_real_escape_string() inside the ", so it consider as string. So remove the " and use it. Try this,
$addEmail = mysqli_real_escape_string($conn,$_POST['newEmail']);
......^
$query ="INSERT INTO Emails (email) VALUES ('$addEmail')";
instead of
$addEmail = "mysqli_real_escape_string($_POST['newEmail'])";
You need to execute the query, not just write it.
$query ="INSERT INTO Emails (email) VALUES ('$addEmail')";
mysqli_query($conn, $query);
If you use a prepared statement, you can save yourself the trouble of escaping:
$stmt = mysqli_prepare($conn, "INSERT INTO Emails (email) VALUES (?)");
mysqli_stmt_bind_param($stmt, "s", $_POST['newEmail']);
mysqli_stmt_execute($stmt);
If you want non-procedural style (aka oop), this would look like the following
$stmt = $conn->prepare("INSERT INTO Emails (email) VALUES (?)");
$stmt->bind_param("s", $_POST['newEmail']);
$stmt->execute();
Get rid of the quotes around your escape function. This turns it into a string instead of actually escaping the value:
$addEmail = mysqli_real_escape_string($conn,$_POST['newEmail']);
$addEmail = mysqli_real_escape_string($conn,$_POST['newEmail']);
http://in2.php.net/mysqli_real_escape_string
string mysqli_real_escape_string ( mysqli $link , string $escapestr )

PHP and sql issue

I have been trying to make my scoreboard system for some online game , It works correctly , So I have added an HTML form that interacts with a php script that connects to my sql database and inserts a name with a percentage into my sql scoreboard table , If I add the names/percentages manually via phpMyAdmin , It works perfectly on the scoreboard , But when I made the html form that asks the user to insert his name and then adds his name into the scoreboard with a percent , IT doesn't add , So here's my html form .
<center><form method="post" action="">
<font color="green">Your name Max length is 15</font> <input type="text" name="username" maxlength="15">
<button style="background-color:red; name="Enter" type="submit" value="HTML">Enter</button></center>
</form>
My PHP Form
<?php
if (isset($_POST['username']))
{
$getname = $_POST['username'];
$percentage = "10";
$link = mysqli_connect("myhost","myusername","mypw","mydatabase") or die("Error " . mysqli_error($link));
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage');" or die("Error in the consult.." . mysqli_error($link));
$result = mysqli_query($link, $query);
}
?>
Scoreboard is the name of my table , Columns are name/percent , Name accepts texts and Percent accepts Integers , Thanks in advance :) .
I tested your code and found that your submit button was one of the things at fault, including an improperly place semi-colon in:
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage');"
Which should read as:
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage')";
Tested using the following form and PHP
<form method="post" action="">
<center>
<font color="green">Your name Max length is 15</font>
<input type="text" name="username" maxlength="15">
<input type="submit" name="submit" value="Submit">
</center>
</form>
<?php
if (isset($_POST['username']))
{
$link = mysqli_connect("myhost","myusername","mypw","mydatabase") or die("Error " . mysqli_error($link));
// $getname = $_POST['username'];
$getname = mysqli_real_escape_string($link,$_POST['username']);
$percentage = "10";
$query = ("INSERT INTO scoreboard (name,percent) VALUES ('$getname',$percentage)");
$result = mysqli_query($link, $query);
if(!$result){
printf("Error message: %s", mysqli_error($link));
}
else {
echo "Data properly inserted with the value of <b>$getname</b> and <b>$percentage</b>";
}
}
?>
NOTE: You will be better off using the code below in order to check if the field is empty. Otherwise, clicking on the submit button without anything inside, will produce an entry in DB with a blank name field.
if (empty($_POST['username'])) {
die("<div align='center'>Enter your name</div>");
}
else
{
// rest of code
Plus as stated by Hanky 웃 Panky, you should sanitize your variables like this, as done in my working example:
$getname = mysqli_real_escape_string($link,$_POST['username']);
Here is a safer (parametrized) method as taken from an example on SO here
Quick note: If you are going to use $percentage = 10; instead of $percentage = "10";
then you will need to use $stmt->bind_param("si", $unsafe_variable,$percentage); otherwise, your percentage will be treated as a string, as opposed to an integer and will be thrown an error. s is for string and i is for integer.
<form method="post" action="">
<center>
<font color="green">Your name Max length is 15</font>
<input type="text" name="username" maxlength="15">
<input type="submit" name="submit" value="Submit">
</center>
</form>
<?php
if (empty($_POST['username'])) {
die("<div align='center'>Enter your name</div>");
}
else
{
$mysqli = new mysqli("myhost","myusername","mypw","mydatabase");
// Check that connection was successful.
if($mysqli->connect_errno > 0) {
die('Connection failed [' . $mysqli->connect_error . ']');
}
$percentage = "10";
$unsafe_variable = $_POST["username"];
$stmt = $mysqli->prepare("INSERT INTO scoreboard (name,percent) VALUES (?,?)");
// TODO check that $stmt creation succeeded
// "s" means the database expects a string
$stmt->bind_param("ss", $unsafe_variable,$percentage);
$stmt->execute();
$stmt->close();
$mysqli->close();
echo "<div align='center'>Data written to DB</div>";
}
?>
Whenever in doubt about the correct usage of any function, take help from php.net first, it has so many examples on the pages about this. Have a look at
http://www.php.net/manual/en/mysqli.real-escape-string.php
http://php.net/mysqli_error
http://www.php.net/manual/en/mysqli.query.php
First sanitize your input value
$getname = mysqli_real_escape_string($link,$_POST['username']);
$percentage = 10;
Then
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname',$percentage)";
$result = mysqli_query($link, $query);
if(!$result){
printf("Error message: %s", mysqli_error($link));
}
This line needs fixed
$query = "INSERT INTO scoreboard (name,percent) VALUES ('$getname','$percentage');" or die("Error in the consult.." . mysqli_error($link));
I've changed it to this
$query = "INSERT INTO scoreboard VALUES ('$getname','$percentage')";
then add or die("Error in the consult.." . mysqli_error($link)); to your query line.
You had a compiler line break in the middle of your variable and you don't need to state the order that your naming values, you just have to put the values in the correct places and it will automatically add them in order.

Categories