I'm developing a web app for movie reviews. I am writing the page where reviews are created and am having issues with the data for a new review being uploaded to the MySQL database. When I submit a new review I get the created successfully message, however the database remains unchanged.
The POST data is gathered by forms located on the same page.
Connect.php:
<?php
$connection = mysql_connect('localhost', 'root', '');
if (!$connection){
die("Database Connection Failed" . mysql_error());
}
$select_db = mysql_select_db('mydb');
if (!$select_db){
die("Database Selection Failed" . mysql_error());
}
?>
Here's my PHP code:
<?php
session_start();
require("connect.php");
if(isset($_SESSION['critic_name'])){
$movie_id=NULL;
if (isset($_POST['reviewmovie']) && isset($_POST['rating'])){
$movie_title = $_POST['reviewmovie'];
$review_title = $_POST['review_title'];
$movie_id = mysql_query("SELECT movie_id FROM Movies WHERE 'movie_title'=".$_POST['reviewmovie']." ") or die(mysql_error());
$mem_id = mysql_query("SELECT mem_id FROM Members WHERE 'critic_name'=".$_SESSION['critic_name']." ") or die(mysql_error());
$rating = $_POST['rating'];
$comments = $_POST['comments'];
$result = mysql_num_rows($movie_id);
$result2 = mysql_num_rows($mem_id);
if(!$result && !$result2){
$query = mysql_query("INSERT INTO `Reviews` (review_id, rating, comments, mem_id movie_id, review_title) VALUES ('$rating', '$comments', '$mem_id', '$movie_id', '$review_title')");
if($query){
$msg = "Review Created Successfully.";
}
}
}
}
?>
Remove the quotes from both WHERE 'movie_title' and WHERE 'critic_name' those are column names and not variables. If you absolutely want to wrap them in something, use backticks `` `.
Plus, change ".$_POST['reviewmovie']." to '".$_POST['reviewmovie']."' and ".$_SESSION['critic_name']." to '".$_SESSION['critic_name']."'
You also forgot a comma in between mem_id and movie_id (which will break your query).
(review_id, rating, comments, mem_id movie_id, review_title)
^ // <- right there
Change it to:
(review_id, rating, comments, mem_id, movie_id, review_title)
Sidenote: Your present code is open to SQL injection. Use mysqli_* functions. (which I recommend you use and with prepared statements, or PDO)
Footnotes:
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Related
I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:
<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
mysql_close($connection); // Closing Connection
?>
Thank you for your help!
You don't ever actually execute your query:
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);
Other things:
if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You are also wide open to SQL injections
You do no error checking. How do you expect to know if there are problems if you don't look for them?
(note: please change server, username, and password for your server information)
<?php
session_start();
$connection = mysql_connect("server","username","password");
if (!$connection) {
die('Connect Error: ' . mysql_error());
}
// Selecting Database
mysql_select_db("database",$connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name,Title,Comments)
VALUES ('$name', '$title', '$comments')";
mysql_query($sql);
mysql_close($connection); // Closing Connection
?>
For security (defense against SQL injection) you can using mysql_real_escape_string function for limit input fields. For example:
$name = mysql_real_escape_string($_POST['name']);
$title = mysql_real_escape_string($_POST['title']);
$comments = mysql_real_escape_string($_POST['comments']);
I know that this is very thoroughly covered on stack overflow, but I cannot figure it out. I am completely new to PHP and SQL commands so please bear with me.
Here is my code:
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$result = mysql_query($connection,"SELECT `first_name` FROM `students` WHERE student_id = '$studentid'");
while($row = mysqli_fetch_array($result))
echo $row['first_name']
I am sure that it is probably something really stupid. I know that i should be using mysqli or something but this is just a test project to teach me some basics.
student_id is from the previous php page, and I want it to lookup student_id and display the first name of the student where I put echo from the table named students, but I get nothing on the page and there is no entry in the error log.
student_id is both the name of the column and the name of the input field on the previous php page.
Also, I don't know if it makes a difference, but the code from $connection to the while statement are in one
Any suggestions?
Thanks.
You're mixing your MySQL APIs, they do "not" mix.
Change mysqli_fetch_array to mysql_fetch_array if you really want to use mysql_*
Plus, put some bracing in:
while($row = mysql_fetch_array($result)) // missing brace
echo $row['first_name'] // <= missing semi-colon
and a semi-colon at the end of echo $row['first_name']
while($row = mysql_fetch_array($result)){
echo $row['first_name'];
}
Also, your DB connection here, goes at the end, not at the beginning: Unlike the mysqli_* method, it goes first. Using mysql_, the connection goes at the end. If you really want to use mysqli_* functions, then you'll need to change all mysql_ to mysqli_ (which follows).
$result = mysql_query($connection,"SELECT `first_name` FROM `students` WHERE student_id = '$studentid'");
which isn't really needed, since a DB connection has been established. (I've placed it at the end though).
$result = mysql_query("SELECT `first_name` FROM `students` WHERE student_id = '$studentid'",$connection);
Plus, use $studentid = mysql_real_escape_string(strip_tags($_POST['student_id']), $connection); for added protection, if you're still keen on using mysql_* based functions.
Add error reporting to the top of your file(s) which will help during production testing.
error_reporting(E_ALL);
ini_set('display_errors', 1);
MySQL (error reporting links)
http://www.php.net/manual/en/function.mysql-error.php
http://www.php.net/manual/en/mysqli.error.php
http://www.php.net/mysqli_error
However...
Here's a full mysqli_ based method: adding mysqli_real_escape_string() to the POST variable.
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = mysqli_connect($serverName, $userName, $password, $dbname)
or die('Unable to connect to Database host' . mysqli_error());
$studentid = mysqli_real_escape_string($connection,$_POST['student_id']);
$result = mysqli_query($connection,"SELECT `first_name` FROM `students` WHERE student_id = '$studentid'");
while($row = mysqli_fetch_array($result)){
echo $row['first_name'];
}
And technically speaking...
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Regarding SQL injection:
Your present code is open to SQL injection. Use mysqli_* functions. (which I recommend you use and with prepared statements, or PDO)
Change all the mysql to mysqli;
Also add a semicolon after your echo and curly braces { and } for your while
Add curly braces around the statement that is supposed to be executed in the while loop.
I'd also suggest you check out mysql_real_escape_string, to avoid SQL Injection ;-)
Also you have to remove the i in mysqli, since youre using the old MySQL functions.
$connection = mysql_connect($serverName, $userName, $password) or die('Unable to connect to Database host' . mysql_error());
$dbselect = mysql_select_db($dbname, $connection) or die("Unable to select database:$dbname" . mysql_error());
$studentid = $_POST['student_id'];
$result = mysql_query($connection,"SELECT `first_name` FROM `students` WHERE student_id = '$studentid'");
while($row = mysql_fetch_array($result)){
echo $row['first_name']
}
Ok, there are a lot of little problems here.
First mysql_query() 's syntax is:
mysql_query(query,connection)
so the connection should be the second argument.
In the query string you have to put `` around the column you are comparing to, like this:
WHERE `student_id` = '$studentid'
^here ^and here
mysql_query() and mysqli_fetch_array() can't work together.
It's either mysql_query() with mysql_fetch_array() or mysqli_query() with mysqli_fetch_array().
You have a missing semi-colon on this row:
echo $row['first_name'] // <- here
Also check if the value from $_POST['student_id'] is the one you expect.
That's what I see for now.
I find using mysqli is much faster to connect and call out your results
$connection = new mysqli($serverName, $userName, $password, $databaseName)
if ($connection->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$studentid = $_POST['student_id'];
$sql = "SELECT `first_name` FROM `students` WHERE student_id = '$studentid'";
$results = $connection->query($sql);
If you're just checking for one student, I would just grab one row
if($results->num_rows == 1){
$row = $results->fetch_assoc();
echo $row['first_name'];
}
If you're trying to grab multi student ids
while($row = $results->fetch_assoc()){
echo $row['first_name'];
}
How do I check insert success in my code?
I tried to test my code below, but it doesn't work. It just returns insert every time.
<?PHP
include("connect.php");
$sql = "INSERT INTO details (name , month , description)
SELECT name , month , description
FROM details_temporary WHERE id = 'xxxxxx'";
$dbQuery = mysql_query($sql);
if($dbQuery) {
echo "insert";
}
else {
echo "not insert";
}
?>
Please, don't use mysql_* functions in new
code.
They are no longer maintained and the deprecation
process has begun on it. See
the red box?
Learn about prepared
statements instead,
and use PDO or
MySQLi - this
article will
help you decide which.
An example using the MySQLi functionality is below:
$mysqli = new mysqli('localhost', 'root', 'password', 'database_name');
$sql = "INSERT INTO details (name, month, description) VALUES ('Alex', 'October', 'My Birthday')";
$result= $mysqli -> query($sql);
$affected = $mysqli -> affected_rows;
if($affected == 1){
echo 'Inserted';
}else{
echo 'Did not insert';
}
Firstly, don't use MySQL functions, they're deprecated and insecure, look in to using MySQLi or PDO.
Secondly, MySQL will only return an error if it failed, so you can just simply run:
if (!$dbQuery) {
die('Invalid query: ' . mysql_error());
}
This will die and print the error if it was unsuccessful.
If you want to check further, you could check mysqli_insert_id() as this will only be set if the query was successful (will only work for inserts, not updates, etc).
You are using INSERT FROM SELECT and if the select has no result then it will insert nothing and still have true in $dbQuery.
Use mysql_affected_rows. : Get number of affected rows in previous MySQL operation
mysql_* functions are deprecated as of php 5.5
If you are working on a new project and NOT changing an old one, it's best to use pdo/mysqli etc.
I don't know if this problem of mine is possible. Is it? I have a library system. I add and edit new books in the Catalog Database. In other words, the Catalog Database is for adding/editing books only. I have another Database (not table) for Borrowing Books. I want to store these books, which are viewed through Catalog DB, to Borrowing DB.
I have a snippet for getting data from Catalog DB
error_reporting(0);
$con = mysql_connect("localhost","root","");
mysql_select_db("catalog", $con);
$acc_number=$_GET["acc_number"];
$query="select * from branch where acc_number = '$acc_number'";
$result=mysql_query($query);
while ($row = mysql_fetch_array($result)) {
//echo $row[1];
}
<textarea name="title" disabled><?php echo $row[1];?></textarea>
And a button for the submission (store to borrowing database). If button is clicked, it's where my problem occurs. I just got a blank page after submitting it. Here is my process.php:
$con = mysql_connect("localhost","root","");
mysql_select_db("catalog", $con);
$acc_number = $_POST['acc_number'];
$title = $_POST['title'];
$sql = mysql_query("select * from books where acc_number='$acc_number'");
while($row=mysql_fetch_array($sql)){
$con = mysql_connect("localhost","root","");
mysql_select_db("borrowing", $con);
$query="INSERT INTO borrowers (title) VALUES ('$title')";
mysql_query($query);
if($query){
header("Location:../librarysystem/books.php");
}
}
You need to create two sql connections, one for each DB. Then simply get the data from one DB (perform operations, if required) and write to the second DB.
First, I suggest that you use MYSQLI or DO since MYSQL is deprecated.
These are suggestions not a fix.
Use only one connect function, you don't need two of them just use the same variable $con.
Add some error checks in there to make sure you are connecting properly
$sql = mysql_query("select * from books where acc_number='$acc_number'") or die ("error message here");
For this
$query="INSERT INTO borrowers (title) VALUES ('$title')";
mysql_query($query);
if($query){
header("Location:../librarysystem/books.php");
}
Try
$query=mysql_query("INSERT INTO borrowers (title) VALUES ('$title')") or die("Could not insert...");
if($query){
header("Location:../librarysystem/books.php");
}
You have two approaches for this:
Create two separate DB connections and manipulate data there. Passing $conn as connection to MySQL queries will work.
Use the same database using different DB prefixes. Say for example, for first DB it should be
mb_ (Manage Books)
and
bb_ (Borrow Books)
If I were at your place, I would have preferred second approach.
I have this problem. This is my PHP code to take one MySQL table and Insert the data into another MySQL table:
<?php
$connect = mysql_connect("host","user","password");
if (!$connect){
die("Failed to connect to the database: ".mysql_error());
}
$kies_bd = mysql_select_db("eraenz_db1",$connect);
if (!$kies_bd){
die("failed to choose from BD: ".mysql_error());
}
$query = "SELECT ListNumber FROM residential";
$result1 = mysql_query($query);
if (mysql_num_rows($result1) >10){
$difference = mysql_num_rows($result1) - 10;
$myQuery = "SELECT * FROM residential ORDER BY id LIMIT 10, $difference";
$result2 = mysql_query($myQuery);
while ($line = mysql_fetch_array($result2)){
mysql_query("INSERT INTO lisitngs
(listnumber, mandatetype, listdate,expirydate, updatedate,virtualtoururl,status,propertyright,agnt_id, erfsize,erf_no, housesize,outbuildingsize, bathroomoptions,closedusergroup,facingoptions,features,kitchenoptions,flatlet,parking,carport,price,numofbath,numofbed, numofgarages, numofkitchens, numofreception,numofstudies,numofdomesticbath,numofdomesticbed,numofoutsidetoil,off_id,ownershiptype, parkingdesc, pooloptions,pool,sellingreason,sfeatureoptions,roofoptions,roomoptions,walloptions,windowoptions, styleoptions,securityoptions,tempcontrol,streetname,streetnumber, suburb, propertycategory,propertytype,ss_name,agentcontactname,province,city, postalcode,email,listingstatus,feedtype, rates, levies)
values ({$line['ListNumber']}','{$line['MandateType']}','{$line['ListDate']}','{$line['ExpiryDate']}','{$line['UpdateDate']}','{$line['VisualTourURL']}','{$line['Status']}','{$line['PropertyCategory']}','{$line['AgentI']}','{$line['SizeOfErf']}','{$line['StandNumber']}','{$line['SizeOfHouse']}','{$line['SizeOfOutBuildings']}','{$line['BathroomOptions']}','{$line['ClosedUserGroup']}','{$line['FacingDescrip']}','{$line['Features']}','{$line['KitchenOptions']}','{$line['Flatlet']}','{$line['Parking']}','{$line['NumOfCarports']}','{$line['ListPrice']}','{$line['NumOfBathrooms']}','{$line['NumOfBedrooms']}','{$line['NumOfGarages']}','{$line['NumOfKitchens']}','{$line['NumReceptionRooms']}','{$line['NumStudies']}','{$line['NumOfDomBathrooms']}','{$line['NumOfDomBedrooms']}','{$line['NumOfOutSideToilets']}','{$line['OfficeId']}','{$line['OwnershipType']}','{$line['ParkingDesc']}','{$line['PoolOptions']}','{$line['Pool']}','{$line['ReasonForSelling']}','{$line['SpecialFeatures']}','{$line['RoofOptions']}','{$line['RoomOptions']}','{$line['WallFinishes']}','{$line['Windows']}','{$line['StyleOptions']}','{$line['SecurityOptions']}','{$line['TempControl']}','{$line['StreetName']}','{$line['StreetNumber']}','{$line['Suburb']}','{$line['PropertyCategory']}','{$line['TypeOfProperty']}','{$line['UnitName']}','{$line['AgentContactName']}','{$line['Province']}','{$line['City']}','{$line['PostalCode']}','{$line['SellerEmail']}','{$line['Status']}','{$line['FeedType']}','{$line['MunRatesTaxes']}','{$line['MonthlyLevy']}')");
mysql_query("INSERT INTO clients
(clnt_title,clnt_name,clnt_surname,clnt_street_name,clnt_street_no,clnt_complex_name,clnt_unit_no,clnt_suburb,clnt_city,clnt_cell,clnt_email,agnt_id,)
values ({$line['SellerTitle']}','{$line['SellerFirstName']}','{$line['SellerSurname']}','{$line['StreetName']}','{$line['StreetNumber']}','{$line['UnitName']}','{$line['UnitNumber']}','{$line['Suburb']}','{$line['City']}','{$line['SellerMobileNumber']}','{$line['SellerEmail']}','{$line['AgentID']}')");
mysql_query("DELETE FROM residential WHERE ListNumber={$line['ListNumber']}");
echo "{$line['ListNumber']} was deleted <br/>";
}
}
mysql_close($connect);
?>
Now not all of these columns are compatible with their counter part column where it is supposed to be inserted into.
My question to you is, how do I save these incompatible strings into a variable and then insert them into the Database Table?
Use Prepared Statements. PHP will convert the type automatically for you, and you're protected against Injection Attacks.
Actually, you should be using Prepared Statements everywhere in your code... building SQL from strings is a bad habit.