replace not updating in database - php

I have a table with id which is the primary key and user_id which is a foreign key but the session is based on this in my code.
I have tried EVERYTHING, so I will post my full code.
The form should insert if there is not a user_id with the same session_id in the table. If there is, it should update.
At the moment, when the user has not visited the form before (no user_id in the table) and data is inserted in, the page returns to the location page: but the data is not inserted in the table. if the user changes the data once it is updated it doesn't change either.
This is the table structure:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
`complete` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
The code I have been using (and failing):
$err = array();
$user_id = intval($_SESSION['user_id']);
// otherwise
if (isset($_POST['doThesis'])) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
// check if current user is banned
$the_query = sprintf("SELECT COUNT(*) FROM users WHERE `banned` = '0' AND `id` = '%d'",
$user_id);
$result = mysql_query($the_query, $link);
$user_check = mysql_num_rows($result);
// user is ok
if ($user_check > 0) {
// required field name goes here...
$required_fields = array('thesis_Name','abstract');
// check for empty fields
foreach ($required_fields as $field_name) {
$value = trim($_POST[$field_name]);
if (empty($value)) {
$err[] = "ERROR - The $field_name is a required field" ;
}
} // no errors
if (empty($err)) {
$id = mysql_real_escape_string($_POST['id']);
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
//replace query
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query))
echo "the query failed";
else header ("location:myaccount.php?id=' . $user_id");
}}}
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");
?>
<br>
<form action="thesis.php" method="post" name="regForm" id="regForm" >
class="forms">
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) { ?>
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
Title of Proposed Thesis<span class="required">*</span>
<textarea name="thesis_Name" type="text" style="width:500px; height:150px"
id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?> </textarea>
</tr>
<tr>
<td>Abstract<span class="required">*</span>
</td>
<td><textarea name="abstract" style="width:500px; height:150px"
type="text" id="abstract" size="600"><?php echo $row_settings['abstract']; ?>
</textarea></td>
</tr>
<?php }
} else { ?>
//shows fields again without echo
I've tried var_dum($query) but nothing appears
PS I know the code isn't perfect but I'm not asking about this right now

I can't see how your replace statement will ever insert the initial row, as the where clause is always going to be false (there won't be a row with that user Id).
I think of you want to use replace you need to replace into thesis (id, userid, etc) without a where clause. If id and userid have a unique constraint and a row for userid exists then it will be updated; if it doesn't exist it will be inserted.
However- if you don't know id- which you won't if you are using auto increment, then I'm not sure you can do this with replace. See http://dev.mysql.com/doc/refman/5.0/en/replace.html
Why don't you check for the existence of a row an then use update or insert?
BTW, is the idea that a user can enter multiple theses into a form, or just one? Your table suggests they can have multiple. If this is what you are trying to achieve then I think you should be storing the id of each thesis in a hidden field as part of the form data. You would then be able to use REPLACE INTO thesis (id, user_id, thesis_name, abstract) VALUES ($id, $user_id, $thesis_name, $abstract) where id is the id of the thesis obtained from each hidden field. If this is not present, i.e. the user has entered a new thesis, then use NULL for id in the insert. This will work using the REPLACE INTO as the id column is auto increment.

Perhaps you mean user_id not id:
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE user_id='{$_SESSION['user_id']}'";
Or if you do mean the id from $_POST['id']
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE id='$id'";
Also instead of REPLACE you should use UPDATE. Im pretty sure its faster because REPLACE basically deletes the row then inserts it again, im pretty sure you need all the fields and values else your insert default values. From the manual:
Values for all columns are taken from the values specified in the
REPLACE statement. Any missing columns are set to their default
values, just as happens for INSERT
So you should use:
$query = "UPDATE thesis
SET thesis_Name='$thesis_Name', abstract='$abstract'
WHERE id='$id'";

You are doing everything right just one thing you are doing wrong
Your replace query variable is $query and you executing $the_query.
you wrong here:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query)) // this is wrong
echo "the query failed";
replace it with:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($query)) // use $query
echo "the query failed";

Related

Avoid duplicates in Mysql through PHP

I have the following table in my database:
CREATE TABLE subjects (
subject_id int(11) NOT NULL AUTO_INCREMENT,
subject text,
PRIMARY KEY (subject_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1;
I also insert the table data from this PHP and it works fine:
<?php
include('Conexion.php');
$subject = "";
if (isset($_POST['reg_subject'])) {
$text = $_POST['text'];
$query = "INSERT INTO subjects (subject) VALUES('$text')";
mysqli_query($conn, $query);
header("Location: index.PHP");
}
?>
The problem is that the user can enter duplicate subjects and I would like to avoid that.
I have tried to show an alert message if the subject already exists, but it continues accepting duplicate subjects. How could I avoid duplicate subjects with the same name?
This is how I’m doing it:
<?php
include('Conexion.php');
$subject = "";
if (isset($_POST['reg_subject'])) {
$text = $_POST['text'];
$subject_check_query = "SELECT * FROM subjects WHERE subject='$subject'";
$result = mysqli_query($conn, $subject_check_query);
$text = mysqli_fetch_assoc($result);
$message = "Already Exists";
if ($text) { // if subject exists
if ($text['text'] === $subject) {
echo "<script type='text/javascript'>alert('$message');</script>";
}
}else{
$query = "INSERT INTO subjects (subject) VALUES('$text')";
mysqli_query($conn, $query);
header("Location: index.php");}
}
?>
Add an if statement around the insert query if it returns a result back from your select query. Also it's an good idea to make use of xdebug this will tell you what happens in your code when you run it.
Keep the insert query part in the else condition
You can create a unique index for the subject_text column:
ALTER IGNORE TABLE subjects ADD UNIQUE (subject_text)
Then change your query to either of the following:
"INSERT IGNORE INTO subjects (subject_text) VALUES('$text')"
Or:
"INSERT INTO subjects (subject_text) VALUES('$text')
ON DUPLICATE KEY UPDATE subject_text = subject_text"
Note that this won't work if your DB already has duplicate values.
For an explanation of the difference between either of these answers, you can look at this question.

how to remove a record with phpmysql

An html form is part of the code which l have intentionally decided not to include. Here is a snapshot of my code:
<?php
require('db.php');
$id=$_REQUEST['id'];
$query = "DELETE FROM new_record WHERE id=$id";
$result = mysqli_query($con,$query) or die ( mysqli_error());
header("Location: view.php");
?>
I don't know if you have an auto incrementing primary key column in your table, but its best if you have one so you can easily update individual records
First you will need to change your SELECT query (or run a new one) and set a WHERE clause to select database entry.
Then change the INSERT script to this:
$insert = $db->prepare("UPDATE people SET firstName = ?, lastName = ?, bio = ? WHERE ID = ?");
$insert->bind_param('sssi', $firstName, $lastName, $bio, $id);
Where $id is the id of the entry in your 'people' database that you got from the SELECT query you ran earlier.
For edit you to have to make a logic, like make this
<td><input type="button" class="btn-info" name="btn" value="Edit"></td>
to a href,
<td>Edit</td>
Supposing id as primary key, and on this new page make a edit form, save it and redirect here.

Update statement not updating table but inserting new entry into table instead

For the life of me I cannot figure out why my update statement will not update the table row but instead it creates a new row. I have an ID column that is the unique identifier and is auto_increment, I am just not sure if you can update an auto_incremented data set the way i am trying to.
I have a form that is echo'ing data from the database into the fields and then am using it to edit the fields and update them.
The code:
<?php
$EntryID = $_GET['Eid'];
$IDlist = mysql_query("SELECT * FROM BD WHERE Id='$EntryID'");
$IDresults = mysql_fetch_array($IDlist);
$update_query = "UPDATE `BD` SET `Id` ='$IDresults['Id']',`EntryTitle` = '$MyTitle',`EntryDescription` = '$MyDescription',`Category` = '$MyCategory' WHERE `Id` ='$EntryID'";
mysql_query($update_query);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else{
header('location: /admin/bd-edit-entry.php?sub=1');
exit();
}
mysql_close($con);
?>
Any help or advice would be a great.
SET `Id` ='$IDresults['Id']'
should be either:
SET `Id` ='$IDresults[Id]'
or
SET `Id` ='{$IDresults['Id']}'
If you turn on error reporting, you should get errors about a bad index.
Or you can leave this column out of the update entirely, since this column isn't changing.

Adding rows to mysql - get sorted randomly - want them on top

I have kind of a "problem" that I do not know how it happened. If I add rows to my table via php it just adds them randomly somewhere. But I want them to be added on top. Instead it justs add them all over the table.
$name = ($_GET["name"]);
$sql = "INSERT INTO $DB_Table VALUES('$name')";
$number = ($_GET["number"]);
$sql = "INSERT INTO $DB_Table VALUES('$number')";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
mysql_query("INSERT INTO $DB_Table (Name,number)
VALUES ('$name','$m_yolo')");
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
There is no such thing as row ordering in a relational table. If you want them ordered, you need to use an ORDER BY clause. You can add a TIMESTAMP column, which you can sort on when you select your data: 11.3.1. The DATE, DATETIME, and TIMESTAMP Types
Create another table but add an ID auto-increment column in it:
CREATE TABLE IF NOT EXISTS `table` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`number` int(10) NOT NULL,
PRIMARY KEY (`id`)
);
Then you can insert new rows like this:
$sql = "INSERT INTO $DB_Table (id, name,number) VALUES ('', '$name', '$number')";
Your new entries will be sorted by id then. You can order them in you select query with:
$sql = "SELECT 'name', 'number' FROM `table` ORDER BY 'id' DESC";
One remark about your code though: it is not safe to directly use the values from $_GET as you do at the beginning of your code. Try using mysql_real_escape_string() for example.

Issues with when writing to database

I'm unable to write to my database while using this script that I whipped up earlier.
<?php
include("db.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Data sent from form, then posted to "admin" table in database
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$author = mysql_real_escape_string($_POST['author']);
$image = mysql_real_escape_string($_POST['image']);
$category = mysql_real_escape_string($_POST['category']);
$sql = "INSERT INTO admin(name,description,author,image,category) VALUES('$name','$description','$author','$image','$category');";
$result = mysql_query($sql);
header("Location: video.php?file=' . $filename . '");
}
?>
And here's my SQL:
CREATE TABLE admin
(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) UNIQUE,
description VARCHAR(50) UNIQUE,
author VARCHAR(50) UNIQUE,
image VARCHAR(50) UNIQUE,
category VARCHAR(50) UNIQUE
);
Everything is submitted with POST via an HTML form. I'm not really sure what I'm doing wrong, so that why I'm wondering what you guys think. Any thoughts?
$result = mysql_query($sql) is not valid (no connection specified).
It needs to be $result = mysql_query($sql, [CONNECTION]);
There may be other issues, but that's an obvious one.
Follow these steps:
Open a MySQL connection (if not omitted in the snippet)
Check your MySQL statement by using var_dump($sql)
Check for the return value of mysql_query(), should be true if the INSERT statement succeeded.
Check for the number of rows affected by the INSERT statement: mysql_affected_rows()
Note:
I'm pretty sure that your INSERT statement fails because all your columns are defined as UNIQUE. As soon as you already have an author with the same name the statement fails!
$auhtor=mysql_real_escape_string($_POST['author']);
The Author variable is spelled wrong.

Categories