Trying to make the switch over to OOP PHP as opposed to my current approach of having a whole load of PHP code in all of my pages.
I've thrown something together which takes a post title, content and status and stores it in a simple database.
I just want to know if I have the right idea or if I'm way off - is it worth me carrying on taking this approach on it?
<?php
$conn = new mysqli('127.0.0.1','root','','admin');
class post {
private $title;
private $content;
private $status;
private $errors;
private $check;
function __construct(){
if(isset($_POST) && !empty($_POST)){
if(empty($_POST['title'])){
$this->errors[] = "Title is required";
}
if(empty($_POST['content'])){
$this->errors[] = "Content is required";
}
if(empty($_POST['status'])){
$this->errors[] = "Status is required";
}
if(empty($this->errors)){
$this->title = $_POST['title'];
$this->content = $_POST['content'];
$this->status = $_POST['status'];
$this->check = true;
} else {
echo "<pre>";
var_dump($this->errors);
echo "</pre>";
}
}
}
function submit(){
if($this->check){
global $conn;
if($conn->connect_error){
die("Connection error: " . $conn->connect_error);
};
$stmt = $conn->prepare("INSERT INTO posts (title, content, status) VALUES (?, ?, ?)");
$stmt->bind_param('sss', $this->title, $this->content, $this->status);
if($stmt->execute()){
echo "Post added succesfully";
} else {
echo "<pre>";
var_dump($stmt);
echo "</pre>";
}
};
}
};
?>
Related
I have this code on "insert.php":
if ($stmt = $GLOBALS['mysqli']->prepare("INSERT INTO table1(iduser, title, msg, anonim, ip, iduniversity) VALUES (?,?,?,?,?,?)")) {
$stmt->bind_param("issisi", $_SESSION['iduser'], $_POST['title'], $_POST['msg'], $anonim, getIP(), $_SESSION['iduniversity']);
if ($stmt->execute()) {
$idmsg = $GLOBALS['mysqli']->insert_id;
$i = 0;
$stmt2 = $GLOBALS['mysqli']->prepare("INSERT INTO tag(idmsg, tag) VALUES(?,?)");
foreach ($tags as $tag) {
if ($tag != '') {
$stmt2->bind_param("is", $idmsg, $tag);
if ($stmt2->execute()) {
$i++;
}
}
}
$stmt2->close();
$stmt->close();
mysqli_close($GLOBALS['mysqli']);
sendFile($idmsg);
header("Location: /public/watch_msg.php?idmsg=" . $idmsg);
exit();
} else {
exit("Ops! Ocorreu algum erro. COD1370");
}
} else {
exit("Ops! Ocorreu algum erro. COD1371");
}
So, everything is working fine, except that sometimes when it redirects to "watch_msg.php" the message seems not to be on the database yet. When this happens, as soon as I refresh the page, everything is there!
First thing I thought is that there could be a race-condition somewhere, but I read in another question that PHP is sequential, and as I close both statements and connection before the redirect (so that used tables should be unlocked), why i'm getting this result somethimes? What i'm doing wrong?
Also, no functions outputs anything, but "sendFile" saves an image if the user sends one, so headers should be fine (it also gives me the error when I comment the function).
Code on watch_msg:
$msg = NULL;
$tags = NULL;
$coments = NULL;
$data_high = date("Y-m-d H:i:s");
$iduser;
if ($loggedin) { //If logged in
$idmsg = filter_input(INPUT_GET, 'idmsg', FILTER_SANITIZE_STRING);
$iduser = $_SESSION['iduser'];
$query = "SELECT * FROM table1 WHERE iduser = ? AND idmsg = ? AND datemsg < ?";
$stmt = $GLOBALS['mysqli']->prepare($query);
$stmt->bind_param("iis", $iduser, $idmsg, $data_high);
if ($stmt->execute()) {
$msg = mysqli_fetch_assoc($stmt->get_result());
if ($msg === NULL) {
exit('This message doesn\'t exists');
}
...
} else {
echo "Error.";
}
}
I have been trying to insert data into my database. I keep getting an error where it isn't recognising what is set. It thinks this is invalid: if (isset($_POST['user_email']) AND isset($_POST['user_choice'])) { so it skips and displays my echo with the values coming through.
Here is my HTML file:
<?php
require_once("../inc/config.php");
$emailAddress ="";
if(isset($_POST["user_email"])) {
$emailAddress = trim($_POST["user_email"]);
$newsletter = trim($_POST["emailLetter"]);
if($emailAddress != "") {
require_once(ROOT_PATH . "inc/images.php");
$results = capture_email($emailAddress, $newsletter);
}
var_dump($results);
exit();
}
?>
<footer id="footer-class">
<form id="footer-form" method="post" action="">
<fieldset>
<legend id="footer-legend">Sign up for...</legend>
<input type="radio" name="emailLetter" id="PC" value="PC" checked><label class="footerlabel" for="PC">Computer</label>
<input type="radio" name="emailLetter" id="Photo" value="Photo"><label class="footerlabel" for="Photo">Photo</label>
<legend id="footer-legend">Newsletter!</legend>
<input id="footer-email" type="email" name="user_email" placeholder="Enter your email address here!" required>
<button type="submit" id="footer-button">Subscribe</button>
</fieldset>
<p>I won't spam you. Promise</p>
</form>
</footer>
</body>
</html>
Here is my PHP function:
<?php
function capture_email($user_email, $user_choice) {
require(ROOT_PATH . "inc/database.php");
if (isset($_POST['$user_email']) AND isset($_POST['$user_choice'])) {
try {
$newsletter = $_POST["$user_choice"];
$email_address = $_POST["$user_email"];
$results = $db->prepare("INSERT INTO userinfo (Email, userOption) VALUES (?, ?)");
$results->bindparam(1, $email_address);
$results->bindparam(2, $newsletter);
$results->execute();
} catch (Exception $e) {
var_dump($e);
exit();
}
} else {
echo "Oops, something went wrong. Here is the user Email: " . $user_email . "<br>Here is the user choice: " . $user_choice;
exit();
}
}
Additional information: Config.php is a file containing variables for the database connection. images.php is a file where I store all my php functions.
Please let me know if you need anymore information.
Thanks
You no need to POST it. Already it is passed as an arguement.
if (isset($user_email) && isset($user_choice)) {
You have to change full code too.
<?php
function capture_email($user_email, $user_choice) {
require(ROOT_PATH . "inc/database.php");
if (isset($user_email) AND isset($user_choice) {
try {
$newsletter = $user_choice;
$email_address = $user_email;
$results = $db->prepare("INSERT INTO userinfo (Email, userOption) VALUES (?, ?)");
$results->bindparam(1, $email_address);
$results->bindparam(2, $newsletter);
$results->execute();
} catch (Exception $e) {
var_dump($e);
exit();
}
} else {
echo "Oops, something went wrong. Here is the user Email: " . $user_email . "<br>Here is the user choice: " . $user_choice;
exit();
}
}
I changed your function a little bit. you passing your post not your variable so it would cause a error. But this should work
function capture_email($user_email, $user_choice) {
require(ROOT_PATH . "inc/database.php");
/*
*You passing the POST, but your surpose to pass thru the var from your function.
*
**/
if (isset($user_email) AND isset($user_choice) {
try {
$newsletter = $user_choice;
$email_address = $user_email;
/**
**Also Sorted your issue out with your speech mark's
**
**/
$results = $db->prepare("INSERT INTO userinfo (Email, userOption) VALUES (?, ?)");
$results->bindparam(1, $email_address);
$results->bindparam(2, $newsletter);
$results->execute();
} catch (Exception $e) {
var_dump($e);
exit();
}
} else {
echo "Oops, something went wrong. Here is the user Email: " . $user_email . "<br>Here is the user choice: " . $user_choice;
exit();
}
Try this and re-run the code.
if(isset($_POST['user_email']) AND isset($_POST['user_choice'])) { ... }
You can use this condition like this :
if (isset($user_email) AND isset($user_choice)) {
try {
$newsletter = $user_choice;
$email_address = $user_email;
$results = $db->prepare("INSERT INTO userinfo (Email, userOption) VALUES (?, ?");
$results->bindparam(1, $email_address);
$results->bindparam(2, $newsletter);
$results->execute();
} catch (Exception $e) {
var_dump($e);
exit();
}
}
Because when you calling this function capture_email(), you have passed two trimed arguments.
there is syntax error :
if (isset($_POST['$user_email']) AND isset($_POST['$user_choice'])) {
replace with :
if (isset($_POST['user_email']) AND isset($_POST['user_choice'])) {
Update try block also :
try {
$newsletter = $_POST["user_choice"];
$email_address = $_POST["user_email"];
$results = $db->prepare("INSERT INTO userinfo (Email, userOption) VALUES (?, ?");
$results->bindparam(1, $email_address);
$results->bindparam(2, $newsletter);
$results->execute();
} catch (Exception $e) {
var_dump($e);
exit();
}
I'm trying to take a form that a user inputs from an HTML site and send the information to a SQL database. I am able to print out the variables after submission, so I know at the very least the variables are set properly. So I have to assume my code to send the content to the database is at fault here.
Here's the code:
//Taking variables from HTML input
if (isset($_POST['group'])) {
$group = $_POST['group'];
} else {
echo $error; return;
}
if (isset($_POST['game'])) {
$game = $_POST['game'];
} else {
echo $error; return;
}
if (isset($_POST['platform'])) {
$platform = $_POST['platform'];
} else {
echo $error; return;
}
if (isset($_POST['player'])) {
$player = $_POST['player'];
} else {
echo $error; return;
}
if (isset($_POST['play'])) {
$play = $_POST['play'];
} else {
echo $error; return;
}
if (isset($_POST['timezone'])) {
$timezone = $_POST['timezone'];
} else {
echo $error; return;
}
$error = 0;
//Retrieving Databse
try {
//userID and password is defined, just hiding it here
$dbh = new PDO("mysql:host=localhost;dbname=userID", "userID", "password");
} catch (Exception $ex) {
die("<p>($e->getMessage())</p></body></html>)");
}
//Inputting content into MySQL
$command = "INSERT INTO teams ( group, game, platform, player, play, timezone )
VALUES ( '$group','$game','$platform','$player','$play','$timezone')";
$stmt = $dbh -> prepare($command);
if ( ! $stmt->execute() ) {
$error = "<b>ERROR:</b> Could not record fields"; echo $error; return;
}
I'm not really sure where I've gone wrong, could be possible it's the tiniest thing or just something I've overlooked.
Thanks in advance for any help, guys!
This is how I did it for my Assignment:
Connecting to MySQL (notice that I dont have any mysql:host=):
$mysqli = new mysqli("localhost", "username", "pass", "database_name");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
Then in your code, when initializing variabels from POST, escape the strings. This will give you some protection against SQL-Injections:
$Name = $mysqli->real_escape_string($_POST["txtName"]);
$Street = $mysqli->real_escape_string($_POST["txtStreet"]);
$City = $mysqli->real_escape_string($_POST["txtCity"]);
Now, prepare a SQL code to insert your params:
$input = $mysqli->query("INSERT INTO customer (MembershipID, Name, Street, City, PostCode, Email, Password, DateJoin, Salt)
VALUES ('". $MembershipID."','".$Name."','".$Street."','". $City."','". $PostCode."','". $Email."','". $Password."','". $DateJoined."','". $Salt."')");
I hope it helps, Good Luck.
I have one problem.I wanted to echo my message ("subject created", "subject creation failed" depending on whether my subject is created or not). The problem is the message is on every page even though setting the $_SESSION["message"] is under if condition . I really don't know where is the problem. I lost probably 2 hours on this...
All includes and requires are included...
This is on my proceeding page:
if(isset($_POST["submit"])) {
$menu_name = mysql_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "INSERT INTO subjects(";
$query .= " menu_name, position, visible ";
$query .= ") VALUES ('{$menu_name}', '{$position}', '{$visible}')";
$result = mysqli_query($connection,$query);
if($result) {
//success //
$_SESSION["message"] = "Subject created";
redirect_to("manage_content.php");
} else {
$_SESSION["message"] = "Subject creation failed";
redirect_to("create_new_content.php");
}
} else {
redirect_to("create_new_content.php");
}
my message function is:
session_start();
function message() {
if (isset($_SESSION["message"])){
$output = $_SESSION["message"];
return $output;
}
}
and after all Im echoing on my manage_content.php and create_new_content.php
<?php echo message(); ?>
You should clear the session when its not needed any more.
E.g.
unset($_SESSION['message']);
Try to clear your $_SESSION message and check if is not empty
function message() {
if (isset($_SESSION["message"]) && !empty($_SESSION["message"])){
$output = $_SESSION["message"];
$_SESSION["message"] = '';
return $output;
}
}
if you show your message only one time, you need to clear the $_SESSION["message"] before return
session_start();
function message() {
if (isset($_SESSION["message"])){
$output = $_SESSION["message"];
// clear the session message
$_SESSION["message"] = null;
// remove message index from $_SESSION
unset($_SESSION["message"]);
return $output;
}
}
For some reason the return doesn't work when the check_em() succeeds. I'm new to php, so I'm at a loss here.
<?php
//Class to handle mysql
class db_handler {
private $db_host = 'localhost';
private $db_name = 'project';
private $db_user = 'project';
private $db_pass = 'dbpassword';
private $db_con_mysql = '';
private $db_con_db = '';
public function check_em($username, $password) {
$db_query = "SELECT password FROM user WHERE name='".$username."' LIMIT 1;";
if($this->db_con_mysql!='') {
$db_query_response = mysql_query($db_query) or die('Query failed: '.mysql_error());
$db_query_return = mysql_fetch_row($db_query_response);
$db_sha1_hash = $db_query_return[0];
echo $db_sha1_hash."<br>";
echo sha1($password)."<br>";
if(sha1($password)==$db_sha1_hash) {
return 'user valid'; //THIS DOESN'T WORK!?!?!?
} else {
return 'no good';
}
} else {
$this->db_connect();
$this->check_em($username, $password);
}
}
//Connect to mysql, then database
private function db_connect() {
$this->db_con_mysql = mysql_connect($this->db_host, $this->db_user, $this->db_pass) || die('Connection failed: '.mysql_error());
$this->db_con_db = mysql_select_db($this->db_name) || die('Could not use'.$this->db_name.'. '.mysql_error());
return;
}
//Disconnect from database and reset vars used to track connection.
private function db_disconnect() {
if($this->db_con_mysql!='') {
mysql_close();
$this->db_con_mysql = '';
$this->db_con_db = '';
return;
}
}
public function fake($some_val) {
if($some_val<6) {
return TRUE;
} else {
return FALSE;
}
}
}
$db_obj = new db_handler();
$val1 = $db_obj->check_em('someuser','password'); //should return 'user valid'
echo "val1:".$val1."<br>";
echo "<br><br>";
$val2 = $db_obj->check_em('someuser','passw0rd'); //should return 'no good'
echo "val2:".$val2."<br>";
echo "<br><br>";
echo "test<br>";
echo $db_obj->fake(4)."<br>";
?>
Results:
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
val1:
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
7c6a61c68ef8b9b6b061b28c348bc1ed7921cb53
val2:no good
test
1
This line needs a return:
return $this->check_em($username, $password);
But a more sensible solution would be to connect to the database inside the if when the connection is null. Really, the whole thing could be better written, but I'll leave it at that.
...
else {
$this->db_connect();
return $this->check_em($username, $password);
}
...
You want to add the return, so that if it fails, then it goes one level deeper and finds another. If that level deeper succeeds, it passes the value up to the level above, which can pass it up and up until it reaches the original function call.