updating database update - php

I am having trouble getting the database to update. Is there something wrong with my sql update statement? I checked the sql statement and it says that there were no records in the database. I am not sure what to do.
<!-- template for mySql database access. -->
<!DOCTYPE html>
<html>
<head>
<title>CRUD</title>
<link href="/sandvig/mis314/assignments/style.css" rel="stylesheet" type="text/css">
</head>
<div class="pageContainer centerText">
<h3>CRUD (Create, Read, Update, & Delete) Database</h3>
<?php
//include database connection
include("DatabaseConnection2.php");
//connect to database
$link = fConnectToDatabase();
//Retrieve parameters from querystring and sanitize
$nameF = fCleanString($link, $_GET['nameF'], 15);
$nameL = fCleanString($link, $_GET['nameL'], 15);
$deleteID = fCleanNumber($_GET['deleteID']);
$updateID = fCleanNumber($_GET['updateID']);
$updateID2 = fCleanNumber($_GET['updateID2']);
//Populate Textbox
if (!empty($updateID)) {
$sql = "SELECT NameL, NameF
FROM customertbl
WHERE custID = '$updateID'";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
$row = mysqli_fetch_array($result);
$strFName2 = $row[NameF];
$strLName2= $row[NameL];
}
?>
<hr>
<form class="formLayout">
<div class="formGroup">
<label>First name:</label>
<input name="nameF" type="text" autofocus value="<? echo $strFName2; ?>">
</div>
<div class="formGroup">
<label>Last name:</label>
<input name="nameL" type="text" value="<? echo $strLName2; ?>">
</div>
<div class="formGroup">
<label> </label>
<button>Submit</button>
<input type="hidden" name="updateID2" value="<? echo $updateID; ?>">
</div>
</form>
<?php
//Update
if (!empty($updateID2))
{
$sql = "UPDATE customertbl
SET NameL = '$strFName2', NameF ='$strLName2'
WHERE custID = '$updateID2' ";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
//Insert
if (!empty($nameF) && !empty($nameL)) {
$sql = "Insert into customertbl (NameL, NameF)
VALUES ('$nameL', '$nameF')";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
//Delete
if (!empty($deleteID)) {
$sql = "Delete from customertbl WHERE CustID= '$deleteID' ";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
}
//List records
$sql = 'SELECT custID, NameF, NameL
FROM customertbl order by custID';
//$result is an array containing query results
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
echo "<p>" . mysqli_num_rows($result) . " records in the database</p>";
?>
<table class="simpleTable">
<tr>
<th>Cust. ID</th>
<th>F. Name</th>
<th>L. Name</th>
<th>Delete</th>
<th>Update</th>
</tr>
<?php
// iterate through the retrieved records
while ($row = mysqli_fetch_array($result)) {
//Field names are case sensitive and must match
//the case used in sql statement
$custID = $row['custID'];
echo "<tr>
<td>$custID</td>
<td>$row[NameF]</td>
<td>$row[NameL]</td>
<td><a href='?deleteID=$custID'>Delete</a></td>
<td><a href='?updateID=$custID'>Update</a></td>
</tr>";
}
?>
</table>
</div>
</body>
</html>

The offending code block
//Update
if (!empty($updateID2))
{
$sql = "UPDATE customertbl
SET NameL = '$strFName2', NameF ='$strLName2'
WHERE custID = '$updateID2' ";
mysqli_query($link, $sql) or die('Insert error: ' . mysqli_error($link));
}
makes references to variables $strFName2 and $strLName2 which are variables that are only populated conditionally.
//Populate Textbox
if (!empty($updateID)) {
$sql = "SELECT NameL, NameF
FROM customertbl
WHERE custID = '$updateID'";
mysqli_query($link, $sql) or die('Delete error: ' . mysqli_error($link));
$result = mysqli_query($link, $sql)
or die('SQL syntax error: ' . mysqli_error($link));
$row = mysqli_fetch_array($result);
$strFName2 = $row[NameF];
$strLName2= $row[NameL];
}
Since the variables $strFName2 and $strLName2 are undefined during the UPDATE SQL query, you're not seeing the desired results.
The query should reference $nameF and $nameL since those variables are always defined (not contained within a conditional) and the form inputs use nameF and nameL in their name attributes.
$sql = "UPDATE customertbl
SET NameL = '$nameF', NameF ='$nameL'
WHERE custID = '$updateID2';";
You also need to fix your DELETE query to reference the column custID and not CustID as it appears your schema uses the former.
$sql = "Delete from customertbl WHERE custID= '$deleteID' ";

Related

PHP - Insert Into Associative Table

I am trying to populate a mysql associative (many to many) table via a form submit. Basically, trying to use this page to associate a "Red Flag" to one-to-many "Products".
Screenshot of input form
FORM
<?php
require 'connect-db.php';
$sql = "SELECT ID, prod_name FROM catalog";
$result = mysqli_query($mysqli, $sql);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p><strong>Add Red Flag:</strong></p>
<form action="addRedFlag.php" method="post" id="rfForm">
<p>Description:
<br/><textarea rows="4" cols="50" name="rfDescription" form="rfForm"></textarea>
<p>Severity: <br/>
<input type="radio" name="severity" value="minor"/>Minor<br/>
<input type="radio" name="severity" value="moderate"/>Moderate<br/>
<input type="radio" name="severity" value="major"/>Major<p/>
<select name="prod_id">
<option value="">Choose a product</option>
<?php while($row = mysqli_fetch_assoc($result)){ ?>
<?php $id = $row['ID']; ?>
<?php $title = $row['prod_name']; ?>
<option value="<?php echo $id; ?>"><?php echo $title; ?></option>
<?php } ?>
</select>
<p/><input type="submit" value="Submit" name="submit" /></form><br>
Reset Form <br>
View Red Flag List<br>
Home
</body>
</html>
PHP HANDLER
<?php
// connect to the database
include("connect-db.php");
$value1 = $_POST['rfDescription'];
$value2 = $_POST['severity'];
$value3 = $_POST['prod_id'];
$sql = "INSERT INTO redFlag (description, severity) VALUES ('$value1', '$value2')";
$sql2 = "SELECT ID FROM redFlag WHERE (description = '$value1')";
$sql3 = "INSERT INTO prod_RF (cat_id, rf_id) VALUES ('$value3', '$value4')";
$result1 = mysqli_query($mysqli, $sql);
$result2 = mysqli_query($mysqli, $sql2);
if ($result1)
{
if ($result2)
{
$row = mysqli_fetch_assoc($result2);
$value4 = $row['ID'];
// echo $value4;
$result3 = mysqli_query($mysqli, $sql3);
if ($result3)
{
echo "success";
}
else {echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);}
}
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
mysqli_close($mysqli);
?>
When executed, the code completes successfully BUT the value of rf_id in prod_RF table is always zero. This is strange because when I uncomment the
echo $value4;
line, the expected value is printed to the screen. For some reason, when I attempt to use that same value ($value4) as input to a SQL query ($sql3), something fails.
Thanks for any suggestions as I'm pretty new to all this.
A better way to do this is to use the MySQL function to get the last insert id so you can skip the second query.
$sql = "INSERT INTO redFlag (description, severity) VALUES ('$value1', '$value2')";
$sql3 = "INSERT INTO prod_RF (cat_id, rf_id) VALUES ('$value3', LAST_INSERT_ID())";
$result1 = mysqli_query($mysqli, $sql);
$result2 = mysqli_query($mysqli, $sql3);
// the $result2 query will insert the rf_id
// so you can test this result to see if it's all successful
That should remove a nice chunk of PHP from your code.
It looks like $value4 is not defined until after the $sql3 string has been crafted. Try defining $sql3 after you have defined $value4.

Fetching data issue from mysql database in this code

I am creating an Invitation Card app for my upcoming event which will be held. My code successfully inserts the data into mysql database named booking having table name data. But there is problem with retrieving. When I fill the form and submit, it saves data in db but generates nothing. It gives following error:
Fatal error: Call to a member function query() on resource in C:\xampp\htdocs\booking\index.php on line 44
Here is my code, please tell me how to resolve this issue. I shall be very thankful to you.
<html>
<body>
<?php
if(isset($_POST['add'])){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn){
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc()){
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
} else {
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
}
$sql = "INSERT INTO data ". "(CNIC, Name, FatherName, PostalAddress) " .
"VALUES('$emp_cnic', '$emp_name', '$emp_fname', '$emp_address')";
mysql_select_db('booking');
$retval = mysql_query($sql, $conn);
if(! $retval) {die('Could not enter data: ' . mysql_error());}
?>
<table border=2>
~~~~~~Your Invitation Card~~~~~
<tr><td>Your Name</td><td><?php
$sql = "SELECT name FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>Your Father Name</td><td>
$sql = "SELECT fname FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>Your CNIC Number</td><td>
$sql = "SELECT cnic FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>Your Postal Address</td><td>
$sql = "SELECT address FROM data";
$result = $conn->query($sql);
echo $result;
?></td></tr><br>
<tr><td>You are informed to approach Location XA-55 at 1800 Thursday with print of this
Invitation card to paticipate in the function. </td></tr><br>
</table>
<?php
mysql_close($conn);
} else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
Name: <input type="text" name="emp_name" id="emp_name"><br>
Father Name: <input type="text" name="emp_fname" id="emp_fname"><br>
CNIC: <input type="text" name="emp_cnic" id="emp_cnic"><br>
Address: <input type="text" name="emp_address" id="emp_address"><br>
<input type="submit" name="add" id="add" value="Submit">
<?php
}
?>
</body></html>
Change
$result = $conn->query($sql);
To
$result = mysql_query($sql);
For more info click here
I think you should be using mysql_query instead of $conn->query
I thin i spotted two errors in your code.
you should use
mysql_query($sql,$conn);
instead of (that was mentioned before)
$result = $conn->query($sql);
You missed a couple of opening php tags in your html table.
Try following code and let me know if it works.
if(! $conn){
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc()){
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
} else {
$emp_name = addslashes($_POST['emp_name']);
$emp_fname = addslashes($_POST['emp_fname']);
$emp_cnic = addslashes($_POST['emp_cnic']);
$emp_address = addslashes($_POST['emp_address']);
}
$sql = "INSERT INTO data ". "(CNIC, Name, FatherName, PostalAddress) " .
"VALUES('$emp_cnic', '$emp_name', '$emp_fname', '$emp_address')";
mysql_select_db('booking');
$retval = mysql_query($sql, $conn);
if(! $retval) {die('Could not enter data: ' . mysql_error());}
?>
<table border=2>
~~~~~~Your Invitation Card~~~~~
<tr><td>Your Name</td><td><?php
$sql = "SELECT name FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>Your Father Name</td><td>
<?php
$sql = "SELECT fname FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>Your CNIC Number</td><td>
<?php
$sql = "SELECT cnic FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>Your Postal Address</td><td>
<?php
$sql = "SELECT address FROM data";
$result = mysql_query($sql,$conn);
echo $result;
?></td></tr><br>
<tr><td>You are informed to approach Location XA-55 at 1800 Thursday with print of this
Invitation card to paticipate in the function. </td></tr><br>
</table>
<?php
mysql_close($conn);
} else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
Name: <input type="text" name="emp_name" id="emp_name"><br>
Father Name: <input type="text" name="emp_fname" id="emp_fname"><br>
CNIC: <input type="text" name="emp_cnic" id="emp_cnic"><br>
Address: <input type="text" name="emp_address" id="emp_address"><br>
<input type="submit" name="add" id="add" value="Submit">
<?php
}
?>
</body></html>

Solving the return value of an SQL Query in an Associative Array

Once again I am at the mercy of your knowledge and hope you can help.
Actual question is the bold italics, however you won't be able to help without reading the information that I've given.
Background to Question - I'm creating a photography website (for my mum) using HTML, CSS, MySQL and PHP. I'm in the process of working on the database, specifically on allowing my mum to insert images into the database using this form (http://i.imgur.com/h4nXFFA.png). She has no idea how to code, therefore I need to make it easy for her.
Database Background (what you need to know) - I've got an image_tbl and album_tbl. The album_tbl is shown here - http://i.imgur.com/4GXh9MP.png - with each album having an ID and Name (forget the 'hidden'). The image_tbl is shown here - http://i.imgur.com/RgC35Nd.png - with the important part (for this question) being the albumName.
Aim - I've managed to populate the 'Insert a New Image' form with the albums from album_tbl (picture shows 'Exploration'). I want her to be able to click the AlbumName (so she knows what album to add to), yet I want the image she inserts to receive the albumID in the database. Here's a Pastebin of my code thus far.
http://pastebin.com/6v8kvbGH = The HTML Form, for helping me be aware of the 1st Form in the code...
http://pastebin.com/4X6abTey = PHP/MySQL Code. Here we have me calling the inputs in the form and using them in 2 SQL Queries. The first Query is aiming to get the albumID of the albumName that was entered, and this is where it goes wrong. The commented out statements (using //) are me error-checking, and albumName is passed on from the form. However, the number of rows returned from the 1st SQL Statement is 0, when it should be 1. This is where I need help as clearly something's wrong with my assoc array ...
2nd Aim - Once the 1st SQL Query is working, the 2nd SQL Query is hopefully going to input the required variables into image_tbl including the albumID I hopefully just got from the 1st SQL Query.
I hope this is all that's required, as far as I'm aware the people who understand this should be able to help with what I've given. Thanks very much in advance!
Jake
Someone asked me to paste the code - HTML Form:
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['albumName'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('admin_db');
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = mysql_query($sql);
echo "<select name='name'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
Inserting the image using PHP/MySQL:
<?php
$username="root";
$password="";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumName = $_POST['albumName'];
// echo "album name is" . $albumName;
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
$albumID = $conn->query($sql);
// echo "Number of rows is " . $albumID->num_rows;
if ($albumID->num_rows > 0) {
// output data of each row
while($row = $albumID->fetch_assoc()) {
echo "Album ID: " . $row["albumID"]. "<br>";
}
} else {
echo "0 results";
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
This line:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = $albumName";
should be:
$sql = "SELECT albumID FROM album_tbl WHERE albumName = '$albumName'";
since the album name is a string.
You should check for errors when you perform a query:
$albumID = $conn->query($sql) or die($conn->error);
You can't use $albumID in the INSERT query. Despite the name of the variable, it doesn't contain an album ID, it contains a mysqli_result object that represents the entire resultset of the query -- you can only use it with methods like num_rows and fetch_assoc() to extract information from the resultset.
What you can do is use a SELECT statement as the source of data in an UPDATE:
$stmt = $conn->prepare("INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT ?, ?, ?, ?, ?, ?, albumID
FROM album_tbl
WHERE albumName = ?";
$stmt->bind_param("sssssss", $name, $dateTime, $caption, $comment, $slideshow, $hidden, $albumName);
$stmt->execute();
Note that when you use a prepared query, you don't need to fix the quotes in $comment (which you should have done using $conn->real_escape_string($comment), not str_replace()).
Just to help you understand, this can also be done without a prepared query.
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`)
SELECT '$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', albumID
FROM album_tbl
WHERE albumName = '$albumName'";
First of all create a single database connection let say
db_connection.php
<?php
$username="root";
$password="1k9i2n8gjd";
$database="admin_db";
$servername="localhost";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully <br><hr>";
Then in your form or any php file that needs database connection you can just include the db_connection.php so that you have one database connection.
Note: I have change the value of option to albumId so that you dont need to query or select based on albumName because you already have the albumID passed in imagesInsert.php via $_POST
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
?>
<html>
<head>
<title>Admin Page | Alison Ryde's Photography</title>
<link rel="stylesheet" type="text/css" href="../../css/style.css">
</head>
<body>
<h2>Insert a new image</h2><br>
<form action="imagesInsert.php" method="POST" enctype="multipart/form-data">
Name of Image: <input type="text" name="name" /><br>
Date: <input type="text" name="dateTime" /><br>
Caption: <input type="text" name="caption" /><br>
Comment: <textarea type="text" name="comment" cols="40" rows="4"></textarea><br>
Slideshow: <input type="text" name="slideshow" /><br>
Choose an Album to place it in:
<?php
$sql = "SELECT albumName FROM album_tbl WHERE hidden = false";
$result = $conn->query($sql);// mysql_query($sql); ?>
<select name='albumName'>; <?php
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['albumID'] . "'->" . $row['albumName'] . "</option>";
}
?> </select>
<input type="submit" name="submit"/><br>
</form>
<h2>Hide the Image</h2><br>
<form action="imagesHidden.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = false";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Hide" name="submit">
</form>
<h2> Renew from Hidden Items </h2><br>
<form action="imagesRestore.php" method="POST" enctype="multipart/form-data">
Title:
<?php
$sql = "SELECT name FROM image_tbl WHERE hidden = true";
$result = $conn->query($sql);//mysql_query($sql);
echo "<select name='name'>";
while ($row = $result->fetch_array()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
echo "</select>";
?>
<input type="submit" value="Renew / Un-Hide" name="submit">
</form>
</body>
</html>
Then in your php code that inserts the data should be like this.
imagesInsert.php
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES ('$name', '$dateTime', '$caption', '$new_comment', '$slideshow', '$hidden', '$albumID')";
$result = $conn->query($sql);
if ($result)
{
echo "Data has been inserted";
}
else
{
echo "Failed to insert";
}
$conn->close();
?>
Another piece of advice is to use prepared statementif your query is build by users input to avoid sql injection
<?php
require_once('db_connection.php');
//include_once('db_connection.php');
$name = $_POST['name'];
$dateTime = $_POST['dateTime'];
$caption = $_POST['caption'];
$comment = $_POST['comment'];
$slideshow = $_POST['slideshow'];
$hidden = false;
$albumID = $_POST['albumName'];
$new_comment = str_replace("'", "''", $comment);
$sql = "INSERT INTO `image_tbl`(`name`, `dateTime`, `caption`, `comment`, `slideshow`, `hidden`, `albumID`) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssss", $name, $dateTime, $caption,$new_comment,$slideshow,$hidden,$albumID);
$stmt->execute();
hope that helps :) good luck

How to delete from my database in PHP/mysql?

Hi there I have many implementations of some php files. All of which have some errors. I will start off with an apology as this is my first question on here and I am certain that I will do this incorrectly as I see many first timers do. I will give as much info as possible and make it relevant to as many people as possible.
I have a database and am having trouble deleting from it. The database is simple. It includes resource_id name room description time_available and uer_id.
Although I expect it to output name description and resources_id it only outputs name and description and it will not let me delete name by resources_id.
How to delete from my database in PHP/mysql?
This is my delete_resources.php
{
<html>
<head>
<title>Delete a Record from MySQL Database</title>
</head>
<body>
<?php
$db_host = "#######";
// Place the username for the MySQL database here
$db_username = "#######";
// Place the password for the MySQL database here
$db_pass = "#######";
// Place the name for the MySQL database here
$db_name = "#######";
//
$con = mysqli_connect("$db_host","$db_username","$db_pass","$db_name");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
mysqli_close($con);
}
$result = mysqli_query($con, "SELECT * FROM resources");
echo 'name' . "\t" . 'description' . "\t" . 'resources_id';
echo "<br>";
while($row = mysqli_fetch_array($result))
{
echo $row['name'] . "\t" . $row['description'] . "\t" . $row['resources_id'];
echo "<br>";
}
// Echoes: string
echo gettype($array);
//
if(isset($_POST['delete']))
{
// Query to select an int column
$resources_id = $_POST['resources_id'];
$sql = "DELETE name From resources ".
"WHERE resources_id = $resources_id" ;
//mysql_select_db('b32_13993766_csc411');
//$retval = mysql_query( $sql, $conn );
if(! $result )
{
die('Could not delete data: ' . mysql_error());
}
else if( $result )
{
echo "Deleted data successfully\n";
}
//mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Resource ID</td>
<td><input name="resources_id" type="text" id="resources_id"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
//
}
You are not executing that delete query. Should look like
$recources_id=intval($resources_id);
$sql = "DELETE FROM resources WHERE resources_id = $resources_id" ;
$result = mysqli_query($con, $sql); // This is missing
$sql_query="Delete from your_table_name where id ='".$your_id."'";
$sql = "DELETE FROM resources WHERE resources_id = $resources_id" ;
Your $result is not relevant at all with your delete query (it is referring to the $result above, not the one with the delete). Try changing to this and see if it works.
if(isset($_POST['delete']))
{
// Query to select an int column
$resources_id = $_POST['resources_id'];
$sql = "DELETE name From resources ".
"WHERE resources_id = $resources_id" ;
$result = mysqli_query($con, $sql); //add this line
//mysql_select_db('b32_13993766_csc411');
//$retval = mysql_query( $sql, $conn );
if(! $result )
{
die('Could not delete data: ' . mysql_error());
}
else if( $result )
{
echo "Deleted data successfully\n";
}
//mysql_close($conn);
}

problem with form php and sql

Ok, so im new in php and sql, and I have this form that submits some names and cities into a database.
I managed to do it, but once a hit the submit button, i get an error:
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1"
but, when i check in phpmyadmin, the new record is there!!, so im not sure what's wrong, thats the problem.
this is the code:
<?php
mysql_connect("localhost", "name", "pass") or die(mysql_error());
echo "Connection to the server was successful!<br/>";
mysql_select_db("db_name") or die(mysql_error());
echo "Database was selected!<br/>";
$resultComuna = mysql_query("SELECT idComuna, nombre FROM comuna ORDER BY nombre ASC");
$resultGiro = mysql_query("SELECT idGiro, nombre FROM giro ORDER BY nombre ASC");
?>
<html>
<head>
<title>TEST</title>
</head>
<body>
<br/><br/>
<form name="form" method="POST" action="test_action.php">
<div align="center">
<!--///////////////// input nombre //////////////////////// -->
NOMBRE CLIENTE:
<input name="nombreCliente" type="text" maxlength="30" size="40"></>
<!-- ///////////////////////////////////////////////////////////// -->
<!-- ////////////////////drop box para giro ///////////////////// -->
GIRO:
<select name="giro">
<?php
while($row = mysql_fetch_assoc($resultGiro)){
echo "<option value=\"".$row['idGiro']."\">".$row['nombre']."</option><br/>";
}
?>
</select>
<!-- ///////////////////////////////////////////////////////////// -->
<!-- ////////////// dropbox para comunas //////////////////////// -->
COMUNA:
<select name="comunas">
<?php
while($row = mysql_fetch_assoc($resultComuna)){
echo "<option value=\"".$row['idComuna']."\">".$row['nombre']."</option><br/>";
}
?>
</select>
<!-- ////////////////////////////////////////////////////////////// -->
<input type="submit" value="Ingresar"> </>
</div>
</form>
</body>
</html>
and the test_action.php is:
<?php
$con = mysql_connect("localhost", "name", "pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("data_base", $con);
$query = mysql_query("SELECT max(idNombre)+1 as id FROM nombre");
$row = mysql_fetch_array($query);
$idMax = $row['id'];
$sql = mysql_query("INSERT INTO nombre VALUES ('".$idMax."','".$_POST['comunas']."',".$_POST['giro'].",'".$_POST['nombreCliente']."')");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "record added";
mysql_close($con)
?>
You're inserting the ID in single quotes:
$sql = mysql_query("INSERT INTO nombre VALUES ('".$idMax."','".$_POST['comunas']."',".$_POST['giro'].",'".$_POST['nombreCliente']."')");
Can you provide the table structure? ID is an integer or a varchar there?
Try changing test_action.php to:
<?php
$con = mysql_connect("localhost", "name", "pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("data_base", $con);
$query = mysql_query("SELECT max(idNombre)+1 as id FROM nombre");
$row = mysql_fetch_array($query);
$idMax = $row['id'];
$query = "INSERT INTO nombre VALUES ('".$idMax."','".$_POST['comunas']."',".$_POST['giro'].",'".$_POST['nombreCliente']."')";
$sql = mysql_query($query);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error().'<br>query: '.$query);
}
echo "record added";
mysql_close($con);
?>
It helps for debugging

Categories