Updating row on mysql php [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I want to update a row on a table and it is not updating.
This is my html and php code :
<?php
if ($_GET) {
if (isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#', '', $_GET['id']);
echo $id;
$query = "SELECT * FROM posts WHERE id='{$id}'";
$result = mysqli_query($connect, $query);
$rows = mysqli_fetch_assoc($result);
} elseif (empty($_GET['id'])) {
header("location: manage_posts.php");
}
}
?>
<form action="modify_post.php?id=<?php echo $id; ?>" method="post">
<h3>Post Title <?php //echo $id; ?></h3>
<input name="title" value="<?php echo $rows['title'];?>" type="text" placeholder="Title here ..." id="title" required>
<h3>Post Content</h3>
<textarea name="content" required placeholder="Title here ..." style="resize: none"><?php echo $rows['content'];?></textarea>
<br/>
<input type="submit" value="Update" id="submit"/>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ($_POST['title'] != "" || $_POST['content'] != "") {
$id = preg_replace('#[^0-9]#', '', $_GET['id']);
$sql = "UPDATE posts SET title='{$_POST['title']}', content='{$_POST['content']}' WHERE id='{$id}'";
$update_result = mysqli_query($connect, $sql);
if (isset($result)) {
echo "<h2>Update successfully, redirecting back ...</h2>";
} else {
echo "Record hasn't been Updated" . mysqli_errno($result);
}
header("location: manage_posts.php");
} else {
echo "<h3>Please fill all fields</h3>";
}
}
?>
This is all what I could came up with !
I don't know where is the problem coming from ?

a) avoid sql injections e.g. with prepared statements + parameters
b) add more error handling and parameter checking.
<?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo 'wrong method';
}
else if ( !isset($_POST['title'], $_POST['content']) ) {
echo 'missing POST parameters';
}
else if ( !isset($_GET['id']) ) {
echo 'missing GET parameter';
}
else if ($_POST['title'] == "" || $_POST['content'] == "") {
echo '<h3>Please fill all fields</h3>';
}
else {
$stmt = $connect->prepare('UPDATE posts SET title=?, content=? WHERE id=?');
if ( !$stmt ) {
trigger_error('prepare failed', E_USER_ERROR);
}
else if ( !$stmt->bind_param('sss', $_POST['title'], $_POST['content'], $_GET['id']) ) {
trigger_error('bind_param failed', E_USER_ERROR);
}
else if ( !$stmt->execute() ) {
trigger_error('execute failed', E_USER_ERROR);
}
else {
echo '# of updated rows: ', $stmt->affected_rows();
}
}
see also
http://docs.php.net/mysqli.error-list
http://docs.php.net/mysqli-stmt.error-list

Related

Issue is header location sending a different URL [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
When the user deletes a project from my website a simple query deletes the attached records from the DB and the user is taken to the home page, which will show a bar at the top of the page "Project Deleted" I do this by having a GET 'err' in the URL, so when err isset the number next to it defines what alert should be shown at the top of the page.
The problem I am having is that the 4th alert is being shown instead of the 8th when this php script is run.
PHP:
if (mysqli_query($conn, "DELETE FROM projects WHERE id='$del' AND user_id ='$user_id'")) {
if (mysqli_query($conn, "DELETE FROM refs WHERE project_id='$del' AND user_id ='$user_id'")) {
setcookie("project_cookie", 0);
header("Location: index.php/?del=8");
}
}
Alerts.php (attached at the top of the header file):
if (isset($_GET['err'])) {
$err = $_GET['err'];
$type = "err";
if ($err == "1") { $alert = "Incorrect Email or Password"; }
elseif ($err == "2") { $alert = "Email address already exists"; }
elseif ($err == "3") { $alert = "All fields require values"; }
elseif ($err == "4") { $alert = "Reference Deleted"; }
elseif ($err == "5") { $alert = '' . '<b>' . "Signup" . '</b>' . ''. " " . "to create and save references"; }
elseif ($err == "6") { $alert = "You can only have 8 projects"; }
elseif ($err == "7") { $alert = "Select a project on the left hand side first"; }
elseif ($err == "8") { $alert = "You have deleted a project"; }
}
I have looked at this for a long while and have no idea why the 4th alert shows instead of the 8th when the PHP Delete script is run.
Change,
header("Location: index.php/?del=8");
To,
header("Location: index.php/?err=8");
Because,
if (isset($_GET['err'])) {
Not,
if (isset($_GET['del'])) {

trouble in inserting record to database using PHP mysqli oops [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am using PHP mysqli to access and insert record to database and also prepared statements but somewhere there is an error i couldn't figure out.. pointing out the mistake will be very much helpful
mailer.php
<?php
class Submit {
const DB = 'localhost',
USER = 'test',
PASS = '123456',
DB_NAME = 'testing';
private $mysql;
public function __construct() {
$this->mysql = new mysqli(self::DB , self::USER , self::PASS , self::DB_NAME);
if ($this->mysql->connect_errno) {
echo "Error: " . $this->mysql->connect_error;
echo "<br>";
echo "Error code: " . $this->mysql->connect_errno;
}
}
public function addRecord($record) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $record->name , $record->message);
if ($stmt->execute()) {
$status = ($stmt->affected_rows == 1) ? true : false;
$stmt->fetch_object();
$stmt->close();
}
}
return $status;
}
}
$submit = new Submit();
$result = null;
if (isset($_POST['submit']) ) {
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$message = isset($_POST['message']) ? trim($_POST['message']) : '';
$result = $submit->addRecord($name,$message);
if ($result) {
echo "Message Saved";
}
}
Also i am using ajax call from an external file containing a form and scripts within that
index.php
<!DOCTYPE html>
<html>
<head>
<title>Contact Form | PHP, AJAX and MySQL</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<form id="submit_form">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="form-control" />
<br />
<label for="message">Message</label>
<textarea name="message" id="message" class="form-control"></textarea>
<br />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
<span id="error_message" class="text-danger"></span>
<span id="success_message" class="text-success"></span>
</form>
</div>
</body>
</html>
<script>
jQuery(function($){
$('form#submit_form').submit(function(e){
e.preventDefault();
var name = $(this).find('#name').val(),
message = $(this).find('#message').val();
if(name == '' || message == '') {
$('#error_message').html("All Fields are required");
}
else {
$('#error_message').html('');
$.ajax({
url:"mailer.php",
method:"POST",
data:{
name: name,
message: message
},
success:function(data){
$("form").trigger("reset");
$('#success_message').fadeIn().html(data).fadeOut(3000);
}
});
}
});
});
</script>
You are giving 2 parameters to your addRecord() method, but it expects only 1. But, it seems it expects an object which you are not initializing so I adjusted it, so it takes the two parameters you are giving it.
public function addRecord($name, $message) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $name , $message);
if ($stmt->execute()) {
$status = $stmt->affected_rows === 1;
}
}
return $status;
}
Also I removed some unnecessary steps in the method:
$status = ($stmt->affected_rows == 1) ? true : false;
$status = $stmt->affected_rows === 1;
The comparison itself will return a boolean, so no need to use an explicit structure.
$stmt->fetch_object();
$stmt->close();
Fetching the object without ever using it is a waste.
When leaving the scope of the method, the garbage collector will unset the stmt.
Code to test the function:
class Submit {
const DB = 'localhost',
USER = 'test',
PASS = '123456',
DB_NAME = 'testing';
private $mysql;
public function __construct() {
$this->mysql = new mysqli(self::DB , self::USER , self::PASS , self::DB_NAME);
if ($this->mysql->connect_errno) {
echo "Error: " . $this->mysql->connect_error;
echo "<br>";
echo "Error code: " . $this->mysql->connect_errno;
}
}
public function addRecord($name, $message) {
$status = false;
$query = "INSERT INTO mytable (name,message) VALUES (?,?)";
$stmt = $this->mysql->prepare($query);
if ( $stmt ) {
$stmt->bind_param('ss', $name , $message);
if ($stmt->execute()) {
$status = $stmt->affected_rows === 1;
}
}
return $status;
}
}
$submit = new Submit();
$result = null;
$name = "dsfdsf";
$message = "message";
$result = $submit->addRecord($name,$message);
var_dump($result); // bool(true)

last if else statement didnt work [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
hye guys..is there anything wrong with my if else statement..i tried input username that already existed in the database,and it work..also same if i left the textbox epmty..but if a tried enter a valid name,it does not read the else statement..can someone help me..i cant find where is the problem
<?php
include 'connect.php';
$username = ($_POST['txtUsername']);
$statement = $mysqli->prepare("SELECT companyUsername FROM tblpartner WHERE companyUsername=?");
$statement->bind_param("s", $username);
$statement->execute();
$statement->bind_result($username);
if ( $statement->fetch()) {
echo '<span class="error"> taken</span>';
} else if(empty($username)) {
echo '<span class="error"> Cannot be empty</span>';
} else
echo '<span class="success"> available.</span>';
?>
I think you're doing it mostly right but just got confused because you bind both the input name and the output result to $username.
You want the username input to be checked for the "empty" condition, and the username output to be checked for NULL to signal that the name is available, if I'm understanding what you want correctly...
So:
$username = ($_POST['txtUsername']);
if (empty($username) || ($username == '')) {
echo '<span class="error"> Cannot be empty</span>';
} else {
$statement = $mysqli->prepare("SELECT companyUsername FROM tblpartner WHERE companyUsername=?");
$statement->bind_param("s", $username);
$statement->execute();
$statement->bind_result($username);
if ( $statement->fetch()) {
echo '<span class="error"> taken</span>';
} else {
echo '<span class="success"> available.</span>';
}
?>

PHP unexpected syntax error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have an error within this PHP else if statement (which is part of an if statement):
Parse error: syntax error, unexpected '}' in /home1/tony1964/public_html/2v2tournaments/action.php
The place where the unexpected '}' is at the end of the code below. I can't figure out why this doesn't work. Thanks in advance for any help.
else if (isset($_GET['do']) && $_GET['do'] === "reg_type_2") {
include('php-riot-api.php');
$summoner_name_input = $_POST['summonername'];
$summoner_name = str_replace(' ', '_', $summoner_name_input);
$summoner_region = $_POST['summonerregion'];
$verify_code_input = $_POST['verify_code'];
$verify_code = str_replace(' ', '_', $verify_code_input);
$instance = new riotapi($summoner_region);
$grab_data = $instance->getSummonerByName($summoner_name);
$decode_data = json_decode($grab_data);
$grab_id = $decode_data->{'id'};
var_dump($grab_id);
$grab_runes = $instance->getSummoner($grab_id,'runes');
$decode_runes = json_decode($grab_runes);
$rune_check = $decode_runes->{'name'};
if ($rune_check = $verify_code) {
$logged_user = $_SESSION['logged_user'];
if (!($stmt = $con->prepare("INSERT INTO `verified_summoners` (`Username`,`SummonerName`,`SummonerRegion`) VALUES (?,?,?)")) || !is_object($stmt)) {
die( "Error preparing: (" .$con->errno . ") " . $con->error);
}
$stmt->bind_param('sss', $logged_user, $summoner_name, $summoner_region);
if($stmt->execute()) {
echo "Successfully Verified! Check out your new list! <a class='content' href='index.php'><span class='button color_yellow'>Return</span></a>";
} else {
echo "Unsuccessful INSERT, Contact Support or Try again...";
}
$stmt->close();
}
} else {
echo "O Dear, It didn't work! Try Again!";
}
}
Formatting your code would answer your question for you.
else if (isset($_GET['do']) && $_GET['do'] === "reg_type_2") {
include('php-riot-api.php');
$summoner_name_input = $_POST['summonername'];
$summoner_name = str_replace(' ', '_', $summoner_name_input);
$summoner_region = $_POST['summonerregion'];
$verify_code_input = $_POST['verify_code'];
$verify_code = str_replace(' ', '_', $verify_code_input);
$instance = new riotapi($summoner_region);
$grab_data = $instance->getSummonerByName($summoner_name);
$decode_data = json_decode($grab_data);
$grab_id = $decode_data->{'id'};
var_dump($grab_id);
$grab_runes = $instance->getSummoner($grab_id,'runes');
$decode_runes = json_decode($grab_runes);
$rune_check = $decode_runes->{'name'};
if ($rune_check = $verify_code) {
$logged_user = $_SESSION['logged_user'];
if (!($stmt = $con->prepare("INSERT INTO `verified_summoners` (`Username`,`SummonerName`,`SummonerRegion`) VALUES (?,?,?)")) || !is_object($stmt)) {
die( "Error preparing: (" .$con->errno . ") " . $con->error);
}
$stmt->bind_param('sss', $logged_user, $summoner_name, $summoner_region);
if($stmt->execute()) {
echo "Successfully Verified! Check out your new list! <a class='content' href='index.php'><span class='button color_yellow'>Return</span></a>";
} else {
echo "Unsuccessful INSERT, Contact Support or Try again...";
}
$stmt->close();
} else {
echo "O Dear, It didn't work! Try Again!";
}
}
-
$stmt->close();
}
}
Should be
$stmt->close();
}

PDO Extract Data in While Loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I'm trying to extract this data into a while loop and its literally returning nothing at all, any ideas whats wrong?
Code:
<?php
if(isset($_GET['id'])){
require('include/db.php');
require('include/init.php');
if(isset($_GET['id']) && is_numeric($_GET['id'])){
$userid = $odb->real_escape_string($_GET['id']);
$result3 = $odb->prepare("SELECT * FROM users where ID = :id");
$result3->bindValue(":id", $userid);
$result3->execute();
while($row3 = $result3->fetch_array(MYSQLI_ASSOC)){
$username=$row['username'];
$email=$row['email'];
$rank=$row['rank'];
$membership=$row['membership'];
$expire=$row['expire'];
$status=$row['status'];
echo "
Username: ".$username."<br />
Email: ".$email."<br />
Rank: ".$rank."<br />
Membership: ".$membership."<br />
Expire: ".$expire."<br />
Status: ".$status."<br />
";
}
} else {
echo "You did not enter an ID!";
}
?>
If you need any information let me know!
Since you are using PDO, some functions have to be updated. Instead of mysql_escape_string(), you can just prepare and bind the value and PDO will escape everything. Also fetch_array() should be fetch() and MYSQLI_ASSOC should be PDO::FETCH_ASSOC.
<?php
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if($id) {
require('include/db.php');
require('include/init.php');
// Prepare && Binding will take care of escaping the string
$result = $odb->prepare("SELECT * FROM users where ID = :id");
$result->bindValue(":id", $id);
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$username = $row['username'];
$email = $row['email'];
$rank = $row['rank'];
$membership = $row['membership'];
$expire = $row['expire'];
$status = $row['status'];
echo "
Username: ".$username."<br />
Email: ".$email."<br />
Rank: ".$rank."<br />
Membership: ".$membership."<br />
Expire: ".$expire."<br />
Status: ".$status."<br />
";
}
} else {
echo "You did not enter an ID!";
}
?>

Categories