I am trying to make a simple form that takes some feedback from the user and adds it to a MySQL database.
The code is as follows -
<?php
$store_id = '4';
$feedbackcontent = 'test';
$rating = '2';
if($feedbackcontent=='' || $rating=='') {
echo 'Feedback and a rating are required';
}
else {
$s1 = new MySqlTable();
$sql = 'INSERT INTO reviews (store_id, FeedbackContent, Rating)
VALUES ("'.$s1->escape($store_id).'", "'.$s1->escape($feedbackcontent).'", "'.$s1->escape($rating).'")';
$s1->executeQuery($sql);
}
?>
But, when I run it in Chrome, I get the following error in the debug console.
500 (Internal Server Error)
Screenshot of the 500 internal server error
Its worth mentioning If I remove the below lines of code and put a simple echo or something, it works OK.
$s1 = new MySqlTable();
$sql = 'INSERT INTO reviews (store_id, FeedbackContent, Rating)
VALUES ("'.$s1->escape($store_id).'", "'.$s1->escape($feedbackcontent).'", "'.$s1->escape($rating).'")';
$s1->executeQuery($sql);
Is there anything obviously wrong with the code or a better way to debug this type of error? Im quite new to PHP, but as far as I can tell this code should work.
I think you miss to set connection with database mysql.
$mysqli = new mysqli("host", "user", "password", "dbname");
Related
Ok, so I've been trying to do this for days, and I've been reading all sorts of tutorials, but I seem to be missing something, because I still can't get it. I'm working on learning about web forms and inserting the form input into the respective database. I'm able to take the info from the form and echo it on the result page, so I know that all works. but I can't seem to get the form input to go into my database. I know the connection works, so there must be something wrong with my syntax.
PHP
//DB Configs
$username = null;
$password = null;
try {
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Set the PDO error mode to exception (what does this mean?)
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`)
VALUES (:name)");
//Insert a Row
$species = $_POST['Species'];
$sql->execute(array(':name'=>$species));
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Query
/*
$input = $db->query("INSERT INTO `NFK_Species` (`Id`, `Name`) VALUES (Null, `$species`)");
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');*/
//Kill Connection
$db = Null;
}
HTML/PHP (web page)
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
if ($sql->execute()){
echo "Data input was successful";
while ($rows = $result->fetch()){
echo $rows['Name']; echo ", ";
}
} else {
echo "Data input failed."; echo mysql_error();
}
?>
This is only my current attempt at doing this. I prefer the attempt I had before, with the bindParam and simple execute(), so if I could get that to work instead, I'd appreciate it. The following example also has the Id column for this table. This is an auto-increment column, which I read doesn't need to be included, so I excluded it from my recent attempt. Is that correct?
Past PHP
//Prepare SQL and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Id`, `Name`)
VALUES (Null, :name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
I've been reading a bunch of tutorials (or trying to), including attempting to decipher the php.net tutorials, but they all seem to be written for people who already have a good handle on this and experience with what's going on, and I'm very new to all of this.
Alright, I was able to figure out my problem, and then successfully insert a row using my code.
Debugging:
So the code posted above was breaking my code, meaning my page wouldn't load. I figured that meant that there was a syntax error somewhere, but I couldn't find it, and no one else had located it yet. Also, that meant that my Error Alerts weren't working to let me know what the problem was. If you look at my original PHP sample, you'll see down at the very bottom there is a single "}" just hanging out and serving no purpose, but more importantly, it's breaking the code (stupid, hyper-sensitive php code). So I got rid of that, and then my Error messages started working. It said I couldn't connect to my database. So I look over my database login syntax, which looked fine, and then you'll notice in my 1st php sample that somehow I'd managed to set my $username and $password to NULL. Clearly that isn't correct. So I fixed that, and next time I refreshed my page, I'd successfully entered a row in my database! (yay)
Note:
In my original php sample, I'd included the Id Column, which is auto-incremented, for the row insertion, with a value of NULL. This worked, and it inserted the row. Then I experimented with leaving it out altogether, and it still worked. So the updated working code below doesn't include the Species Id.
Working code:
<body>
<h1>Inserting a New Species into Database:</h1>
<h3>Results</h3>
<?php
//DB Configs
$username = root;
$password = root;
try {
//Connect to Database
$db = new PDO("mysql:host=localhost;dbname=Testing3", $username, $password);
//Enable PDO Error Alerts
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Prepare SQL statement and bind parameters
$sql = $db->prepare("INSERT INTO `NFK_SPECIES` (`Name`) VALUES (:name)");
$sql->bindParam(':name', $species);
//Insert a Row
$species = $_POST['Species'];
$sql->execute();
// Echo Successful attempt
echo "<p class='works'><b>" . $species . "</b> successfully added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Gather updated table data
$result = $db->query('SELECT * from `NFK_Species` ORDER BY `Id` DESC');
//Kill Connection
$db = Null;
while ($rows=$result->fetch()){
echo $rows['Id']; echo " - "; echo $rows['Name']; echo "</br>";
}
?>
<body>
I have a page which allows a user to create an entry and insert it into the database via submitting a form through PHP.
I have had the page working in the past, and it worked perfectly, but now for some reason it has stopped working. Basically, I submit the form, and there are no error messages, but my entry does not appear in the database.
Here is my PHP:
<?php // add_entry.php
session_start();
include_once 'creds.php';
$con=mysqli_connect("$db_hostname","$db_username","$db_password","$db_database");
if (isset($_POST['group'])){
$lab = $_SESSION['labname'];
$author = $_SESSION['username'];
$name = $_POST['entryName'];
$group = $_POST['group'];
$protocol = $_POST['protocol'];
$permission = $_POST['permission'];
$array = $_POST['protocolValues'];
// $filearray = $_POST['fileArray']; Don't forget to add '$filearray', to your query after ARRAY.
$project = $_POST['project'];
$query = "INSERT INTO data (protocol, name, lab, author, uniquearray, usergroup, project, permissionflag) VALUES ('$protocol', '$name', '$lab', '$author', '$array', '$group', 'project', '$permission')";
mysqli_query($con, $query);
mysqli_close($con);
}else{
echo "FAILURE. GROUP WAS NOT SET.";
}
?>
Any ideas as to why this may be happening?
Thanks in advance!
In addition to the accepted answer which I applaud, this 'project' in your VALUES()
is missing the $ sign - therefore, it's not being passed as a variable but as a simple string.
so change it to '$project'
otherwise, the value entered in DB will be project and not the intended POST value from your form.
You're also not checking for errors, which is crucial during the development stages of a project.
Add error reporting to the top of your file(s)
error_reporting(E_ALL);
ini_set('display_errors', 1);
which will signal any errors found in your code.
try to add
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
after $con=mysqli_connect(...);
and replace this
mysqli_query($con, $query);
with this
if (!mysqli_query($con, $query)) {
printf("Errormessage: %s\n", mysqli_error($con));
}
you will be able to debug the problem (if related to the query)
I am trying to insert values for longitude, latitude and descriptions of locations generated from google maps (the ID value is to be generated within PhpMyAdmin. When I run the following code I always get the "error" message. If I "echo $sql;" before //insert values into database then I get the intended output so I guess it must be a problem with transferring to the database.
I'm using phpMyAdmin from within MAMP so am not sure if that is causing any issues of whether I'm missing something obvious in the code? I'm fairly new to PHP so may have missed something obvious! Any help would be much appreciated.
<?php
$con=mysqli_connect("localhost", "root", "root", "googlemaps") or die("could not connent to db");
error_reporting(0);
for($i=0;$i<count($_POST['value']);$i=$i+3)
{
$sql .= "(NULL, '".$_POST['value'][$i]."', '".$_POST['value'][$i+1]."', '".$_POST['value'][$i+2]."'),";
}
//remove last comma
$sql = substr($sql,0,-1);
//insert values into database
$query = "INSERT INTO 'googlemaps'.'values' ('id', 'lat', 'lng', 'des') VALUES " .$sql;
$status = mysqli_query($con, $query);
if($status)
echo "inserted";
else
echo "error";
?>
I'm using Alban Xhaferllari AJAX multiple uploader and I have an issue with inserting data to my database. Here is the link to the upload.php. here is my code that it doesn't work.
function success($file_path)
{
$conn = new mysqli("localhost", "xxxxx", "xxxxxxxx");
$conn->set_charset("utf8");
$conn->select_db("xxxxxxx");
$id = $conn->query("INSERT INTO Galerie (Poza) VALUES($file_path) ");
}
This is the code from their website dunno what's wrong cause I dont get any error but still it doesn't insert.
Please correct following it works for me
$id = $conn->query("INSERT INTO Galerie (Poza) VALUES('$file_path') ");
I am using a dedicated server through 1 and 1 and the PHP code as below will not insert the data into the database.
All connections to database are correct.
$id = $_REQUEST['id'];
$content = $_REQUEST['content'];
mysql_query("UPDATE `content` SET `content` = '$content' WHERE `id`='$id'");
When I test on my local server all works fine, there is something about the server that will not allow me to upload. I am connecting using a very general method
$connection = mysql_connect("localhost",
"root",
"password");
mysql_select_db("dbname", $connection);
1) Turn on error reporting by putting this on the top of your PHP script:
error_reporting(E_ALL);
2) Run your script. Any errors? If yes, proceed according to the error message you get.
3) Double check that your variables are actually defined (you are getting them from the request, you cannot be sure request actually contains values you are trying to use).
4) Your SQL query is very dangerous. Use mysql_real_escape_string() or prepared statements. Don't put quotes around integer values.
5) Edit your script to look more like this:
error_reporting(E_ALL);
$id = (isset($_REQUEST['id']) && !empty($_REQUEST['id'])) ? $_REQUEST['id'] : NULL;
$content = (isset($_REQUEST['content']) && !empty($_REQUEST['content'])) ? $_REQUEST['content'] : NULL;
try{
if(NULL === $id){
throw new Exception('$id is NULL');
}
if(NULL === $content){
throw new Exception('$content is NULL');
}
$id = mysql_real_escape_string($id);
$content = mysql_real_escape_string($content);
$sql = "UPDATE content SET content = '$content' WHERE id = $id";
// connect to database
// ...
mysql_query($sql);
}catch(Exception $e){
echo '<p style="color: red;">',$e->getMessage(),'</p>';
}
Ddebugging for beginners...
You haven't posted any errors, is error reporting turned off? Debugging is much easier with error reporting turned on.
error_reporting(E_ALL);
We'll also want to see what the actual query we're trying to run in the database. Perhaps the variables haven't been properly escaped (Contains illegal characters).
$query = "UPDATE table SET name='$name' where id='$id'";
echo $query;
mysql_query($query);
My guess is that you have to mysql_real_escape_string(); both variables.
Also you pass $id as a string, it's probably an integer.
You're mishandling transactions.