Issues with when writing to database - php

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.

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.

No getting result from query on host database

On my test machine the query for finding a users last_name and id works fine. I cannot figure out why it will not work on my host.
For this table
students(
id VARCHAR(5) NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
grade SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (id)
);
I run this query and there is no problem.
$sql="SELECT * FROM $tbl_name WHERE last_name ='$myusername' and id ='$mypassword'";
$result = #mysqli_query ($dbc, $sql);
mysqli_close($dbc);
if(!is_object($result) || $result->num_rows != 1)
{
$errors[] = 'No entries found, maybe capitalize your last name.';
}
else
{
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['username'] = $_POST['username']; //last name
$_SESSION['firstName'] = $row['first_name'] ;
}
On the host though, there is no rows in the result.
However, I ran this set of code and all the entries show up. Why does the query not work?
$sql="SELECT * FROM $tbl_name";
$num_results = mysqli_num_rows($result);
for ($i=0; $i<$num_results; $i++)
{
$row = mysqli_fetch_assoc ($result);
print stripslashes($row['last_name'])." ".stripslashes($row['id']);
}
By the way, the username is a persons last name and their password is their id. I am not that experienced with PHP and MySql, but this logically does not make sense to me.
Should be using mysqli_query.
Just please be sure to change $link with the connection result (of mysqli_connect).
Code:
$sql = "SELECT * FROM $tbl_name";
$result = mysqli_query($link, $sql);
$num_results = mysqli_num_rows($result);
$i = 0;
while ($row = mysqli_fetch_assoc ($result)) {
print stripslashes($row['last_name'])." ".stripslashes($row['id']);
$i++;
}
I am not sure about it, but I think you're using the wrong language for a mysql host, for example the loop isn't supposed to be in SQL language. As far as I know, this looks like C or C++ (it could depend of what kind of database you're currently using).
But what you need to know is that with this query you need to know the exact name and the exact password. Just in case, do this.
The query in SQL language, should be written it as it follow :
SELECT * FROM students WHERE last_name = "ifyouknowit" OR password="ifyouknowit";
You'll be sure to have at least one result, and it would show up the whole concerned lines as you're calling the " * ". So you don't really need a parameter, as the password is supposed to be unique to everyone.. (Theorically).
In another case, try to add one more column and call it USERID or something like this, to set a unique referent number. So you'll be sure not to be confusing between two people having the same name and last name which could happen easily.
Also, be sure to use the write syntax correctly about the name (like the capital letters are important somehow).
And I notice also that you don't have any password column in this table. Where is it stored? In anycase, with this query you'll still have results.
"students(
id VARCHAR(5) NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
grade SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (id)
);"
You should call the password database from where it's stored. Put more informations about the other tables and then I'll write a complete query for you.
This code was clearing the variables values so nothing was being searched for in the query. I thought this was standard code that should be used, apparently not.
//prohibit sql injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

replace not updating in database

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";

php - duplicate entry

what should do if the entry are doubled?
<?php
require_once('auth.php');
session_start();
$exam = $_SESSION['exam'];
$subject_id = $_SESSION['exam'];
$_SESSION['sub'] = $subject_id;
$subject_title = $_POST['subject_title'];
$subject_description = $_POST['subject_description'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_compre', $con);
$sql = "INSERT INTO examsubjectrecord_table(subject_id , subject_title ,
subject_description)
VALUES ('$subject_id','$subject_title', '$subject_description')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
header("location: addsubject.php?exam=".$exam ."");
}
?>`
Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\compre\admin\addsubjectacc.php on line 4
**Error: Duplicate entry '1' for key 'PRIMARY'**
It depends on yout application business-logic.
You can notify a user about a duplicated entry or silently update information with INSERT ... ON DUPLICATE KEY UPDATE ... SQL statement.
In your database you have a primary key of subject_id which cant have duplicates.
If you need to have duplicates in the subject_id column then you should add a column and set it as a primary key in your database. For example add another column unique_id and set it to auto_increment and as a primary key for row identification.
Basically, you'll first want to check if the value you're trying to insert into your primary key field already exists.
So if you primary key field is subject_id, you'd need to check if that already exists by doing a select query followed by PHP's mysql_num_rows function. For example:
$subject_id = 1337;
$check = mysql_query("SELECT `subject_id` FROM `examsubjectrecord_table` WHERE `subject_id`=" . $subject_id);
// See if anything was returned
if(mysql_num_rows($check) > 0) {
// We have something with this subject_id already!
echo "Cannot insert duplicate subject!";
} else {
// All clear, run your INSERT query here
}
Which column is your primary key? I'm going to assume that's subject_id. This needs to be unique for each row in your table. The easiest way to ensure this is to use AUTO_INCREMENT and then avoid inserting the subject_id at all. It will be assigned automatically.
If you need to find out what the ID of new subjects is, you can use mysql_insert_id.

PHP/MYSQL - Check whether it have duplicated record before inserting new record

Suppose I have a table called "device" as below:
device_id(field)
123asf15fas
456g4fd45ww
7861fassd45
I would like to use the code below to insert new record:
...
$q = "INSERT INTO $database.$table `device_id` VALUES $device_id";
$result = mysql_query($q);
...
I don't want to insert a record that is already exist in the DB table, so how can I check whether it have duplicated record before inserting new record?
Should I revise the MYSQL statement or PHP code?
Thanks
UPDATE
<?php
// YOUR MYSQL DATABASE CONNECTION
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'device';
$table = 'device_id';
$db_link = mysql_connect($hostname, $username, $password);
mysql_select_db( $database ) or die('ConnectToMySQL: Could not select database: ' . $database );
//$result = ini_set ( 'mysql.connect_timeout' , '60' );
$device_id = $_GET["device_id"];
$q = "REPLACE INTO $database.$table (`device_id`) VALUES ($device_id)";
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Since I understood well your question you have two ways to go, it depends how you would like to do the task.
First way -> A simple query can returns a boolean result in the device_id (Exists or not) from your database table. If yes then do not INSERT or REPLACE (if you wish).
Second Way -> You can edit the structure of your table and certify that the field device_id is a UNIQUE field.
[EDITED]
Explaining the First Way
Query your table as follow:
SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'
then if you got results, then you have already that data stored in your table, then the results is 1 otherwise it is 0
In raw php it looks like:
$result = mysql_query("SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'");
if (!$result)
{
// your code INSERT
$result = mysql_query("INSERT INTO $database.$table `device_id` VALUES $device_id");
}
Explaining the Second Way
If your table is not yet populated you can create an index for your table, for example go to your SQL command line or DBMS and do the follow command to your table:
ALTER TABLE `your_table` ADD UNIQUE (`device_id`)
Warning: If it is already populated and there are some equal data on that field, then the index will not be created.
With the index, when someone try to insert the same ID, will get with an error message, something like this:
#1062 - Duplicate entry '1' for key 'PRIMARY'
The best practice is to use as few SQL queries as possible. You can try:
REPLACE INTO $database.$table SET device_id = $device_id;
Source

Categories