minichat in php not saving or showing any texts etc [duplicate] - php

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
Hey i want to create a minichat just as exercise but for some reason it A) goes to a seperate page after i hit Send and doesnt return and B) does NOT post anything nor does it save anything to the database. Minichat form his here:
<!DOCTYPE html>
<html>
<head>
<title>Mini-Chat</title>
<meta charset="UTF-8">
<style>
form
{
text-align: center;
}
</style>
<body>
<form action="minichat-post.php" method ="post">
<p>
<label for="username">Username</label> : <input type="text" name="username" id="username"/><br>
<label for="message">Message</label> : <input type="text" name="message" id="message"/><br>
<input type="submit" value="Send"/>
</p>
</form>
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=minichat', 'root', '');
}
catch(Exception $e)
{
die('Error :'.$e->getMessage());
}
$response = $bdd->query('SELECT username, message FROM minichat ORDER BY ID DESC LIMIT 0, 10');
while ($data = $response->fetch())
{
echo '<p><strong>' . htmlspecialchars($data['username']) . '</strong> : ' . htmlspecialchars($data['message']) . '</p>';
}
$response->closeCursor();
?>
</body>
</html>
Here is the Post form:
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=minichat', 'root', '');
}
catch(Exception $e)
{
die('Error :'.$e->getMessage());
}
$req = $bdd->prepare('INSERT INTO minichat (username, message VALUES (?, ?)');
$req->execute(array($_POST['username'], $_POST['message']));
header('Location: mini-chat.php');
?>
in my PHP DB i got a 2 fields, username and message, i added a new one saying ID but that did not help either.

You missed a closing ')' in INSERT query. Change this line
$req = $bdd->prepare('INSERT INTO minichat (username, message VALUES (?, ?)');
to
$req = $bdd->prepare('INSERT INTO minichat (username, message) VALUES (?, ?)');

Related

How to insert data in database using PDO? [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
Is there any error in my code? I tried to insert articles but it's not being inserted.
It will be great if someone can check my code and tell me about my mistakes (I'm learning).
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in']))
{
//display add page
if (isset($_POST['title'], $_POST['content']))
{
$title = $_POST['title'];
$content = $_POST['content'];
if (empty($title) or empty($content))
{
$error = 'All fields are required';
}
else
{
$query = $pdo->prepare('INSERT INTO articles (article_title, article_content, article_timestamp) VALUES (?, ?, ?)');
$query->bindValue(1, $title);
$query->bindValue(2, $content);
$query->bindValue(3, time());
$query->execute();
header('Location: index.php');
exit();
}
}
?>
<html>
<head>
<title>CMS Tuterial</title>
<link rel="stylesheet" href="../assets/style.css" />
</head>
<body>
<div class="container">
CMS
<br />
<h4>Add Article</h4>
<?php
if(isset($error))
{
?>
<small style="color:#aa0000;"><?php echo $error; ?>
<br /> <br />
<?php
}
?>
</small>
<form action="add.php" method="post" autocomplete="off">
<input type="text" name="title" placeholder="Title" /><br /><br />
<textarea rows="15" cols="50" placeholder="Content" name="content"></textarea><br /><br />
<input type="submit" value="Add Article" />
</form>
</div>
</body>
</html>
<?php
}
else
{
header('Location: index.php');
}
?>
This doc explains the PDOStatement::bindValue that you might want to check. Then, you might want to change your codes to something similar to this, and it may work:
session_start();
include_once '../includes/connection.php';
if (isset($_SESSION['logged_in'])) {
//display add page
if (isset($_POST['title'], $_POST['content'])) {
$title = $_POST['title'];
$content = $_POST['content'];
if (empty($title) or empty($content)) {
$error = 'All fields are required';
} else {
$query = $pdo->prepare('INSERT INTO articles (article_title, article_content, article_timestamp) VALUES (?, ?, ?)');
$query->bindValue(1, $title, PDO::PARAM_STR);
$query->bindValue(2, $content, PDO::PARAM_STR);
$query->bindValue(3, time(), PDO::PARAM_INT);
$query->execute();
header('Location: index.php');
exit();
}
}
}
Edit:
If you only wish to see, queries are being executed, you might remove the ifs and test it, then you can add any if that is necessary. Maybe, similar to:
session_start();
include_once '../includes/connection.php';
$title = $_POST['title'];
$content = $_POST['content'];
var_dump($title);
var_dump($content);
$query = $pdo->prepare('INSERT INTO articles (article_title, article_content, article_timestamp) VALUES (?, ?, ?)');
var_dump($query);
$query->bindValue(1, $title, PDO::PARAM_STR);
$query->bindValue(2, $content, PDO::PARAM_STR);
$query->bindValue(3, time(), PDO::PARAM_INT);
$query->execute();

Uncaught Error: Call to a member function prepare() on boolean ... Stack trace: #0 {main} thrown in [duplicate]

This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 3 years ago.
I'm trying to use Ajax and PHP to send my input data database without refreshing the page. But I am getting this error and it's been couple of hours of me solving this issue but I still can't. Please help me. Thanks!
This is my index.php file where I placed my ajax script and html codes.
$(document).ready(function() {
$('#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
url: 'insert.php',
method: 'post',
data: $('form').serialize(),
dataType: 'text',
success: function(strMessage) {
$('#result').text(strMessage);
$('#myForm')[0].reset();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h5 class="alert-heading">
ADD INFORMATION
</h5>
<hr>
<form id="myForm" method="post" action="">
<div class="form-group">
<label>Full name</label>
<input type="text" autofocus="on" class="form-control" name="fullname" placeholder="Enter your name here" required>
</div>
<div class="form-group">
<label>Address</label>
<input type="text" class="form-control" name="address" placeholder="Address" required>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div class="alert alert-success" role="alert" id="result"></div>
And here's my insert.php file
<?php
try {
include_once 'classes/Db.php';
$fullname = addslashes($_POST['fullname']);
$address = addslashes($_POST['address']);
$sql = "INSERT INTO users (null, fullname, address) VALUES ('$fullname', '$address')";
$stmt = $conn->prepare($sql);
$stmt->execute();
} catch (PDOException $e) {
echo "ERROR IN INSERTING DATA! : " . $e->getMessage();
}
?>
And my classes/Db.php file
<?php
$localhost = 'localhost';
$dbname = 'test_icon';
$username = 'root';
$password = '';
try {
$sql = 'mysql:localhost=' .$localhost. '; dbname=' .$dbname;
$stmt = new PDO($sql, $username, $password);
$conn = $stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "CONNECTION FAILED: " .$e->getMessage(). '<br/>';
die();
}
?>
First fix ;
$sql = 'mysql:localhost=' .$localhost. '; dbname=' .$dbname;
Should be :
$sql = 'mysql:host=' .$localhost. '; dbname=' .$dbname;
Then :
$sql = "INSERT INTO users (fullname, address) VALUES (?,?)";
$stmt = $conn->prepare($sql);
$stmt->execute([$fullname,$address]);
When you create your PDO instance you are setting the connection to the result of setAttribute which is a boolean indicating whether the function succeeded or not. You should be setting it to the output of the constructor:
$conn = new PDO($sql, $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

PHP MySQL - User inputs name and corresponding id is inserted

I have two tables, members and games. In members is data such as member_id, first_name, last_name, etc.
What I'm trying to do is create a form for games, where the user can input the first and last names of the member who participated (in one string, not separately) and some PHP code queries this name, finds the corresponding id and stores this instead. Of course, member_id is a foreign key in games, but the users aren't going to know the member's id, they will only know their name.
If anyone could explain how I might go about doing this I would greatly appreciate it.
Form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
</head>
<body>
<form action="action.php" method="post">
<p>
<label for="date">Date:</label>
<input type="date" name="date" id="date">
</p>
<p>
<label for="duration">Duration:</label>
<input type="time" name="duration" id="duration">
</p>
<p>
<label for="member_id">Member Name:</label>
<input type="text" name="member_id" id="member_id">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
Action:
<?php
// database connection
include 'pdo_config.php';
try {
// new pdo connection
$conn = new PDO($dsn, $user, $pass, $opt);
// prepare statement and bind parameters
$stmt = $conn->prepare("INSERT INTO games (date, duration, member_id)
VALUES (:date, :duration, :member_id)");
$stmt->bindParam(':date', $date);
$stmt->bindParam(':duration', $duration);
$stmt->bindParam(':member_id', $member_id);
// post data
$date = $_POST['date'];
$duration = $_POST['duration'];
$member_id = $_POST['member_id'];
// execute statement
$stmt->execute();
// success or error message
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
This should work.
Ask the user to input the member name in the form instead of the member id. Then make a first query to the database to get the member id from the member name.
Have in mind that it's not a good idea to search the member id from its name, because you could have more than one member whit the same name.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
</head>
<body>
<form action="action.php" method="post">
<p>
<label for="date">Date:</label>
<input type="date" name="date" id="date">
</p>
<p>
<label for="duration">Duration:</label>
<input type="time" name="duration" id="duration">
</p>
<p>
<label for="member_name">Member Name:</label>
<input type="text" name="member_name" id="member_name">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
// database connection
include 'pdo_config.php';
try {
// new pdo connection
$conn = new PDO($dsn, $user, $pass, $opt);
// post data
$date = $_POST['date'];
$duration = $_POST['duration'];
// Note that the explode only works well if user inputs one blank space to separate the name
// You can try to improve the separation method or better use two different inputs in the form
$nameArray = explode(" ", $_POST['member_name']);
$first_name = $nameArray[0];
$last_name = $nameArray[1];
$statement = $conn->prepare("SELECT member_id FROM members WHERE first_name = :first_name AND last_name = :last_name");
$statement->execute(array(':fisrt_name' => $first_name, ':last_name' => $last_name));
$row = $statement->fetch();
$member_id = $row['member_id'];
// prepare statement and bind parameters
$stmt = $conn->prepare("INSERT INTO games (date, duration, member_id)
VALUES (:date, :duration, :member_id)");
$stmt->bindParam(':date', $date);
$stmt->bindParam(':duration', $duration);
$stmt->bindParam(':member_id', $member_id);
// execute statement
$stmt->execute();
// success or error message
echo "New record created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

Fatal error: Call to undefined method PDO::error()

apparently this works for my teacher but for me it gives the error Fatal error: Call to undefined method PDO::error()
Code in Question:
<!DOCTYPE html>
<html>
<head>
<title>Mini-Chat</title>
<meta charset="UTF-8">
<style>
form
{
text-align: center;
}
</style>
<body>
<form action="minichat-post.php" method ="post">
<p>
<label for="username">Username</label> : <input type="text" name="username" id="username"/><br>
<label for="message">Message</label> : <input type="text" name="message" id="message"/><br>
<input type="submit" value="Send"/>
</p>
</form>
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');
}
catch(Exception $e)
{
die('Error :'.$e->getMessage());
}
$response = $bdd->query('SELECT username, message FROM minichat ORDER BY id DESC LIMIT 0, 10');
while ($data = $response->fetch())
{
echo '<p><strong>' . htmlspecialchars($data['username']) . '</strong> : ' . htmlspecialchars($data['message']) . '</p>';
}
$response->closeCursor();
?>
</body>
</html>
more specifically it gives me the error line 31 which is the while loop:
while ($data = $response->fetch())
going nuts here as it worked once already with a small correction but now i cant seem to find out where to make it.
EDIT: Error is now away but it wont save any messages in the database nor display them after hitting Send.
here the post php file:
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=minichat', 'root', '');
}
catch(Exception $e)
{
die('Error :'.$e->getMessage());
}
$req = $bdd->prepare('INSERT INTO minichat (username, message VALUES (?, ?)');
$req->execute(array($_POST['username'], $_POST['message']));
header('Location: ./mini-chat[conflit].php');
?>
add this
fetch(PDO::FETCH_ASSOC);
in here
fetch()
PDOStatement::fetch
Also check for post
<?php
if(isset($_POST['username']) && isset($_POST['message'])) {
try
{
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', '');
}
catch(Exception $e)
{
die('Error :'.$e->getMessage());
}
$response = $bdd->query('SELECT username, message FROM minichat ORDER BY id DESC LIMIT 0, 10');
while ($data = $response->fetch())
{
echo '<p><strong>' . htmlspecialchars($data['username']) . '</strong> : ' . htmlspecialchars($data['message']) . '</p>';
}
$response->closeCursor();
}
?>

Prevent duplicate SQL entries and insert data to SQLite in PHP

On submit/refresh the same predefined data in my array is added. How do i stop it being added more than once. I'd like to get rid of the data in my array if possible and just catch user input from the form which then is submitted to the array but i'm not sure how. Also how can i get my form to submit to my SQLite database, i think i need to add an INSERT INTO statement somewhere. Any help would be nice as i need this finished soon. :(
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Input</title>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php
try {
$dbh = new PDO('sqlite:mydb.sqlite3');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec("CREATE TABLE IF NOT EXISTS test (
name VARCHAR(30),
gender VARCHAR(30),
age INTEGER)"
);
$data = array( //Want to remove this prewritten data and store user input instead.
array('name' => 'Daniel', 'gender' => 'Male', 'age' => '21')
);
$insert = "INSERT INTO test (name, gender, age)
VALUES (:name, :gender, :age)";
$stmt = $dbh->prepare($insert);
foreach ($data as $m) {
$name = $m['name'];
$gender = $m['gender'];
$age = $m['age'];
$stmt->bindParam('name', $name);
$stmt->bindParam('gender', $gender);
$stmt->bindParam('age', $age);
$stmt->execute();
}
$result = $dbh->query('SELECT * FROM test');
$dbh = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
<div id="wrapper">
<div class="banner1">
<h2>Input</h2>
</div>
<form id="form" method="post">
Name:<br>
<input type="text" name="name[0]"/> <br>
Gender:<br>
<input type="text" name="gender[0]"/> <br>
Age:<br>
<input type="number" name="age[0]" min="1" max="99"/> <br>
<input id="submit" type="submit" value="Input">
</form>
</div>
<div id="results">
<div class="banner2">
<h2>Results</h2>
</div>
<div class="data">
<?php
unset($_POST['submit']);
$data=$_POST;
foreach ($result as $row) {
echo $row['name'] . " ";
echo $row['gender'] . " " ;
echo $row['age'] . "<br>" . " ";
}
?>
</div>
</div>
</body>
</html>
Here is a screenshot so you can grasp an idea of the form and how i'd like it to work. The results section is just generated from the array so i can see what is being inputted, but i'd like the input form to send data to the SQLite database that i have created/connected to above. Thank you.
First you have to test if Post exists
And second, check if the user already exist
if (isset($_POST)) {
// check for existing user
// Save
}

Categories