So I am running an error check, since my edit post function is not working, and this is the message I am getting
Fatal error: Uncaught mysqli_sql_exception: Unknown column 'trewfh' in 'field list' in C:\xampp\htdocs\Final\Forum\editpost.php:55 Stack trace: #0 C:\xampp\htdocs\Final\Forum\editpost.php(55): mysqli_query(Object(mysqli), 'UPDATE hw7_foru...') #1 C:\xampp\htdocs\Final\Forum\editpost.php(39): editpost(72, 'trewfh') #2 {main} thrown in C:\xampp\htdocs\Final\Forum\editpost.php on line 55
What a confusing error message! It is echoing out exactly what I want it to (the id =72 and the random string =trewfh) however nothing occurs in terms of updating my post. The $connectDB variable comes from including my connection file and universally works everywhere with no issues. I was hoping someone could see what I am not. Thanks for your time and assistance!!!
<?php
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(-1); mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX);
include 'header.php';
include 'dbconnect.php';
//GATHER MY POST THAT MATCHES THE POST THE USER CLICKS TO EDIT AND DISPLAY TO THEM!
$sql = "SELECT forumpost_ID, forumpost_Text
FROM hw7_forumpost
WHERE forumpost_ID =" . mysqli_real_escape_string($connectDB, $_GET['eid']);
$result = mysqli_query($connectDB,$sql);
if(!$result){ echo 'Something went wrong, please try again later.'; }
else{
while($row = mysqli_fetch_array($result)){
echo'<form action="" method="post">';
echo'<div>';
echo'<textarea name="contents" rows="15" cols="50">'.$row[1].'</textarea>';
echo'</div><div>';
echo'<input type="submit" value="Add Post">';
echo'</div>';
}echo '</form>';
}
if(isset($_POST['contents'])){
$contents = trim($_POST['contents']);
editpost($_GET['eid'], $contents);
echo ('Your post has been updated!');
header('index.php');
die();
}
include 'footer.php';
/********************************************
edit function
**********************************************/
function editpost($id, $contents){
global $connectDB;
$id = (int)$id;
$contents = mysqli_real_escape_string($connectDB, $contents);
$sql = "UPDATE hw7_forumpost SET forumpost_Text=".$contents." WHERE forumpost_ID= ".$id;
$result = mysqli_query($connectDB, $sql);
}
?>
My update should be saying hey database Update hw7_forumpost SET forumpost_Text = 'Trewfh' WHERE forumpost_ID = The correct id it's Getting via $_GET. Its reading everything fine like I said when it's echoing. Something random is happening along the way through
"UPDATE hw7_forumpost SET `forumpost_Text` = -->'<--".$contents."-->'<-- WHERE `forumpost_ID` = ".$id;
It was a simple case of forgetting to place a ' ' in between calling contents as David has pointed out. Thank you David!!!!
Related
I understand that similar general questions exist, but none of them follow my specific set of circumstances, and none of them really provide a solution.
Inside the same folder on the server, I have two files: "quiz_maker.php"
and "master_data.php."
I send a JSON object to "master_data.php" from "quiz_maker.php" with the following Ajax code:
if(localStorage.getItem("JSON Question Data Object") != null){
//The JSON object was stringified before saving to localStorage.
var dataString = localStorage.getItem("JSON Question Data Object");
$.ajax({
method: "POST",
url: "master_data.php",
data: { jsonDataObject: dataString },
success: function(msg){
console.log(msg + "\n");
}
});
}
Then, in "master_data.php", I receive it as follows:
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
$masterQuestionData = json_decode($masterQuestionData, TRUE);
//Perform MySQL Queries here.
}
else{
echo "not set";
}
When I run the code on "quiz_maker.php", the Ajax success handler fires, and I receive the string "set" in the console as I would expect. However, if I look at the "master_data.php" file, the string "not set" gets echoed out, and the following notice is displayed:
Notice: Undefined index: `jsonDataObject` in
/home/sites/5a/0/03891393e8/public_html/master_data.php on line 35
Furthermore, all the MySQL queries execute perfectly using the allegedly "undefined index" "jsonDataObject".
What would be the reason why Ajax's success handler fires, gives me the string "set" and all of the queries work, but I get an undefined index notice on master_data.php?
Thank you.
As requested, here is the whole master_data.php file:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
$booleanSuccessfulOne = false;
$booleanSuccessfulTwo = false;
$servername = "[REDACTED]";
$username = "[REDACTED]";
$password = "[REDACTED]";
// Create connection
$link = mysqli_connect($servername, $username, $password, $username);
// Check connection
if (mysqli_connect_error()) {
$alert = "Oops! We're having trouble publishing your questions and
answers right now. Please try again later.";
die($alert);
}
if(isset($_POST['jsonDataObject'])){
echo "set";
$masterQuestionData = $_POST['jsonDataObject'];
// Unescape the string values in the JSON array
$masterQuestionData = $_POST['jsonDataObject'];
// Decode the JSON array
$masterQuestionData = json_decode($masterQuestionData, TRUE);
$maxQuestions = $masterQuestionData["statistics"][0]["totalQuestions"];
for($i = 1; $i <= $maxQuestions; $i++){
$question = $masterQuestionData["block"][$i-1]["question"];
$answer = $masterQuestionData["block"][$i-1]["answer"];
$query = "INSERT INTO `master` (`id`, `question`, `solution`)
VALUES('".$i."', '".$question."', '".$answer."') ON DUPLICATE KEY
UPDATE `id` = '".$i."', `question` = '".$question."', `solution` =
'".$answer."'";
mysqli_query($link, $query);
}
$query = "DELETE FROM `master` WHERE `id` > '".$maxQuestions."'";
mysqli_query($link, $query);
}
else{
echo "not set";
}
There shouldn't be spaces in the item key for localstorage. The rest of my suggestions are in the chat comments.
localStorage.getItem("JSON Question Data Object");
Can you try the following below and let us know what happens? Change all of your getItem() and setItem() to have no spaces.
localStorage.getItem("JSON");
I believe it should fix up this issue because the rest of your ajax & php looks fine.
That said, you can use bracket notation if you want
localStorage['JSON Question Data Object']
if (isset($_GET['id'])) {
$movie_id=$_GET['id'];
$sql="SELECT * FROM movies WHERE movie_id='$movie_id'";
$run_sql=mysqli_query($connect,$sql);
while ($row=mysqli_fetch_assoc($run_sql)) {
$id=$row['movie_id'];
$name=$row['Name'];
$desc=$row['Description'];
echo "<div id='breadcrumb'><a href='index.php'>Home</a> > <a href='movies.php'>Movies</a> $name</div>
<div id='description'>
<h1>$name</h1>
<p>$desc</p>";
}
}
this is the code and its shows nothing except the url ID which is passing through GET no other details are showing no errors either ,
The main issue is with the URL.
Your URL is single.php?movie=3 and you're checking for $_GET['id']. So change your id by movie.
For the future, you have to code that is SQL Injection free and follow the Instruction given by #RiggsFolly.
In these situations you should add some error checking to your code. In fact you should always be error checking
<?php
// some people develop on LIVE servers so make sure
// all error reporting is on while developing a script
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
function single_page(){
global $connect;
if (isset($_GET['id'])) {
$movie_id=$_GET['id'];
$sql="SELECT * FROM movies WHERE movie_id='$movie_id'";
$run_sql=mysqli_query($connect,$sql);
if ( ! $run_sql ) {
// output the error returned by the database
echo 'SQL ERROR: ' . mysqli_error($connect);
exit;
}
while ($row=mysqli_fetch_assoc($run_sql)) {
$id=$row['movie_id'];
$name=$row['Name'];
$desc=$row['Description'];
echo "<div id='breadcrumb'><a href='index.php'>Home</a> > <a href='movies.php'>Movies</a> $name</div>
<div id='description'>
<h1>$name</h1>
<p>$desc</p>
</div>";
}
}
}
This should at least tell you what the error is, if in fact it is generating an error in the compilation or execution of the query.
I Dont think I wrote the code correctly. Can someone look at this? I am new to php!
<?php
// Create Connection
$connect = mysqli_connect('localhost','root','test123','joomla');
// Check Connection
if(mysqli_connect_errno($connect)) {
echo 'Failed to connect to DataBase| '. mysqli_connect_error();
}
?>
I added if(issets($_GET['rp_id'])) to the if rp_id does not exist in the url parameter - it just closes the database
<?php
if(issets($_GET['rp_id]')) {
$rp_id = htmlspecialchars($_GET["rp_id"]);
// open record with evdet_id =$rp_id
$result = mysqli_query($connect,"SELECT * FROM n0dap_jevents_vevdetail WHERE evdet_id =".$rp_id);
while($row = mysqli_fetch_array($result)):
$value = $row['google_map'];
echo $value;
endwhile;
}
$connect->close();
//if the rp_id does exist the go ahead and run the top otherwise close it.
} else {
$connect->close();
}
?>
if(issets($_GET['rp_id]))
Looks like you made a typo on isset().
Call to undefined function issets()
This means you're trying to call issets() as a function, which it is not.
The function that you are looking for is isset(). If you replace issets() with isset(), you will not longer get that error message.
A little help if possible. I have a Page that pulls from two data tables (MySQL) and one function is providing empty results.
function ShowClient() {
global $agent;
$sql = 'SELECT * FROM nuke_bulletins WHERE user=\'' . $agent . '\' AND isActive="Y" ORDER BY id';
$client = mysql_query($sql) or die('ERROR: OOPS Something went wrong' . mysql_error());
echo '<center><p><b>Current Campaigns</b></p>';
// Pull the loop and display the data
while($row = mysql_fetch_array($client)) {
$agent = stripslashes($row['user']);
$campaign = stripslashes($row['id']);
$title = stripslashes($row['title']);
echo '<p><b>' . $title . '</b></p>';
}
echo '<p>Click the Campaign Title to get the Bulletin Code</p><p> </p>';
echo '<p align="center"><b>Return to All Client\'s</p>';
}
The $agent variable is pulled from a main function that creates a url based on the user ($agent).
What am I doing wrong here?
$agent is a global variable. Using global variables is generally considered bad practice, as this could be getting set or unset somewhere before this function is called.
Have you checked the PHP Error Log to see if you are getting any errors?
If no errors in log I would look to see if $agent conatins a value either by echoing to screen (if dev environment) or dumping the value in the error log file to see if it actually contains anything. http://www.php.net/manual/en/function.error-log.php
Then I would look at the SQL itself; do the Column headings in your table nuke_bulletins match the $row array keys exactly for instance are they the same case?
$row['title']
or
$row['Title']
Here we go...
Don't use the mysql extension. It is unmaintained and officially deprecated
Don't use globals. Relying on external state makes for smelly code
You're overwriting said global variable ($agent) in a loop. Terrible idea.
or die must die ~ http://www.phpfreaks.com/blog/or-die-must-die
I wouldn't recommend using echo within a function. Makes for spaghetti code
Your HTML is a bit of a mess
Here's my suggestion using the mysqli extension
function getCampaigns(mysqli $con, $agent) {
if (!$stmt = $con->prepare("SELECT id, title FROM nuke_bulletins WHERE user = ? AND isActive = 'Y' ORDER BY id")) {
throw new Exception($con->error, $con->errno);
}
$stmt->bind_param('s', $agent); // if the user column is a integer, use 'i' instead
if (!$stmt->execute()) {
throw new Exception($stmt->error, $stmt->errno);
}
$stmt->bind_result($id, $title);
$campaigns = []; // or array() if you're on PHP < 5.4
while ($stmt->fetch()) {
$campaigns[$id] = $title;
}
return $campaigns;
}
Now you can call this function like this...
<?php
// assuming you have a mysqli instance in a $con variable, eg $con = new mysqli(...)
// and an $agent variable
$campaigns = getCampaigns($con, $agent);
?>
<p><strong>Current Campaigns</strong></p>
<?php foreach ($campaigns as $id => $title) : ?>
<p>
<a href="bullies2.php?op=ShowCampaign&id=<?= $id ?>">
<strong><?= htmlspecialchars($title) ?></strong>
</a>
</p>
<?php endforeach ?>
<p>Click the Campaign Title to get the Bulletin Code</p>
<p> </p>
<p align="center"><strong>Return to All Client's</strong></p>
And, as always, your development environment should have the following properties set in your php.ini file
display_errors = On
error_reporting = E_ALL
I have the following PHP code:
<?php
//Connection to PDO Database
?>
<form method="post" action="">
<p>Busisness telephone 1</p><input id="business_telephone_01" name="business_telephone_01" tabindex="auto" value="<?php echo $result['business_telephone_01']; ?>" type="text" />
<input name="submit" type="submit" value="Save Changes"></form>
<?php
//Get from Form
if((empty($_POST['submit']) === false)){
$business_telephone_01 = $_POST['business_telephone_01'];
//Formating of telephone numbers
$message = 'This message I want to display';
echo 'This is another message';
}
echo $message;
//Code to update table through PDO
?>
Regardless of where I do the echo whether it is echo 'This is another message'; within the conditional brackets or _ echo $message;_ outside the brackets nothing is being echoed and no error is being displayed.
The html form and the PDO are working correctly and are being updated but nothing is being echoed. No error is being shown in the error log.
UPDATE:
If I use if((empty($_POST['submit']) === false)){ I get PHP
Notice: Undefined variable: hello
If I use if (isset($_POST['submit'])) { I get PHP Notice:
Undefined variable: hello
If I use if (!isset($_POST['submit']))
{ it gives me a list of undefined variables that I use e.g. from
my code above business_telephone_01
My full code
if((empty($_POST['submit']) === false)){
//Get from Form
$address_building_name = $_POST['address_building_name'];
$address_building_number = $_POST['address_building_number'];
$address_street = $_POST['address_street'];
$address_locality = $_POST['address_locality'];
$address_postcode = $_POST['address_postcode'];
$address_country = $_POST['address_country'];
//Formating of address
$address_building_number = strtoupper($address_building_number);
$address_building_number = str_replace(' ','',$address_building_number);
$address_building_name = ucwords($address_building_name);
$address_street = ucwords($address_street);
$address_locality = ucwords($address_locality);
$address_postcode = strtoupper($address_postcode);
$address_country = ucwords($address_country);
echo 'Hello';
$good = 'Good bye';
}
echo $good;
I'd be willing to bet $message isn't being echo'd because it's never initialized. (The if block, where it is supposed to be initialized, is not being executed because the conditional is failing.)
First off, you should use isset to determine if a POST variable has been submitted:
if (isset($_POST['submit'])) {
Or, to see if it has not been submitted:
if (!isset($_POST['submit'])) {
Secondly, you should enable error reporting on your program and let us know what errors (if any) you are getting:
error_reporting(E_ALL);
ini_set("display_errors", 1);
You can add these two lines to the very top of your script, right after the opening <?php line, which should help shed some light on the situation.
The problem could be that the $message variable is never set within your if statement.
If the 'if' condition is not matched, then $message is never set and you will not be able to echo the value.
To test, you could set the $message variable to some value before you start your if statement.
$message = 'condition failed';
if(isset($_POST['submit'])){
....
$message = 'This message I want to display';
}
echo $message;
If the condition is met, it will echo "This message I want to display".
If the condition fails, it will echo 'condition failed';
A quick dirty test, but it will tell you if the $message variable will be initialized inside your 'if' statement.