Check To See A Match In MySql - php

I have a form which has a textbox with an attribute called ref. once this is submitted, it updates on of my fields in the database. I have this code working and fine but what i need now is for it to check if the data entered into the textbox exists in the database and if it does, then it should notify the user to choose another reference. here is my code for the php end:
$ref = mysql_real_escape_string($_REQUEST['ref']);
$id = $_GET['public'];
$con = mysql_connect("localhost", "*****", "******");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('*****', $con);
$sql = "UPDATE public SET ref = '$ref' WHERE public_id = '$id'";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
}
any ideas guys?
thanks

You can get the number of rows affected:
$rowsAffected = mysql_affected_rows($con);
if($rowsAffected) {
//something WAS changed!
}
else {
//NOTHING was changed ... :-(
}
Also I would watch out for Bobby Tables
You might want to use mysqli or PDO's prepared queries for what you want to do.
Based on OP's comment below:
...
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
$rowsAffected = mysql_affected_rows($con);
if($rowsAffected) {
echo '<hr><h2>Reference Number Has Been Assigned Successfully</h2><hr>';
}
else {
//show some error message?
}
}

In this case First you run a select command to search for the record with particular reference number. If the result is eof , then run insert command. If not EOF then send a warning to the user saying reference number exist and choose another one.

Related

check username in databse and update[html,mysql,php]

i have been trying since yesterday, and almost covered all questions regarding this matter in Stackoverflow plus googling, but so far nothing is working with me, i try to check username availability before updating the username in database, however, it wont check and always update the username directly without error message regarding not availability of the name..
here my code
//new connection
$con = new mysqli("localhost", "student", "student", "C14D5");
if ($con->connect_errno) { //failed
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
//success
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['clientN'])) {
$query = mysqli_query("SELECT client_name FROM clients WHERE client_name='".$_POST['clientN']."'");
if (mysqli_num_rows($query) != 0) {
echo "<script>
alert('Username is not available, please select another username.');
</script>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
// run sql
$sql ="UPDATE `clients` SET `client_name` = '".$_POST['clientN']."' WHERE `client_ID` = '".$_POST['SelectClient']."'";
if ($con->query($sql) === TRUE) {
echo "<h3> New record created successfully</h3>";
header('Location: '. $_SERVER['HTTP_REFERER'] );
} else {
echo "Error : " . $sql . "<br>" . $con->error;
}
$con->close();
}
}
You can use the mysqli_num_rows() function to avoid data duplication in your database
use this code :
//specify the database connection factors as usual ,then
$uname = $_POST['your_username_field'];
$sql = "SELECT * FROM your_db where username='$uname'";
//the variable 'sql' will store the resultset of the query
$num_row = mysqli_num_rows($sql);
// the 'num_row' will store the number of rows which matches your $sql resultset. So if it is greater than '0' then the data already exists
if( $num_row > 0)
{
// display 'username exists error'
}
else
{
// Insert user name into your database table
}
If the num_rows is greater than 0 ,then the username is already present in your database table . So at that case throw error. else INSERT the user name into your database and display success message .

How can I retrieve the auto increment number from the related thread's row on "threads" table?

I have a table for "threads" and a table for "comments" on my database. Both tables have an auto increment ID column, timestamp etc. There is also a "THREAD ID" column where I'd like to INSERT thread's IDs in the "comments" table.
My question is: how can I retrieve the auto increment ID number of the related thread's row from "threads" table and INSERT this number to the "comments" table's "THREAD ID" column every time when I insert a comment. So I can create a link between "comments" and "threads".
I'm somewhat beginner at PHP and I'd like to learn with the explanation of the code. Like which string is for what, which method is for what..
<?php
/*show error codes*/
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'On'); //On or Off
/* database info*/
define('DB_NAME', 'imageboard');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
$link1 = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link1) {
die('Could not connect: '.mysqli_error());
}
$db_selected = mysqli_select_db($link1, DB_NAME);
if (!$db_selected) {
die('Can\'t use' . DB_NAME . ': ' . mysqli_error());
}
//when pressed submit
if (isset($_POST['replySubmit'])) {
//buton ve textarea def
$deger = $_POST ['replyComments'];
$deger2 = $_POST ['replyNickName'];
$deger3 = $_FILES ['replyUserFile']['name'];
// WANT TO DEFINE THREAD ID HERE
//deger4 = $_POST [];
// SEND TO DATABASE
$sql1 = "INSERT INTO newReply (COMMENT, NAME, IMAGENAME) VALUES ('$deger', '$deger2', '$deger3')";
//connection check
if (!mysqli_query($link1, $sql1)) {
die('Error: ' . mysqli_error());
} else {
header('Location: ./thread.php');
}
}
?>
<?php
if(isset($_FILES['replyUserFile'])) {
$uploadName1 = $_FILES['replyUserFile']['name'];
$uploadTmp1 = $_FILES['replyUserFile']['tmp_name'];
$uploadType1 = $_FILES['replyUserFile']['type'];
// CORRECTION
$uploadName1 = preg_replace("#[^a-z0-9.,]#i", "_", $uploadName1);
// FILES TO directory
if(!$uploadTmp1) {
die("can't send...");
} else {
move_uploaded_file($uploadTmp1, "./images/$uploadName1");
}
$link1 = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link1) {
die('Could not connect: '. mysqli_error());
}
$db_selected1 = mysqli_select_db($link1, DB_NAME);
if (!$db_selected1) {
die('Can\'t use' . DB_NAME . ': ' . mysqli_error());
}
//INSERT INTO tables
$sql1 = "INSERT INTO images (USERIMAGENAME) VALUES ('$uploadName1')";
//connection check
if (!mysqli_query($link1, $sql1)) {
die('Error: ' . mysqli_error());
} else {
// CHANGE THE NAME OF THE IMAGE FILE IN THE DIRECTORY TO DATABASE ID NUMBER
$last_id = mysqli_insert_id($link1);
$ext1 = pathinfo("./images/$uploadName1", PATHINFO_EXTENSION);
rename("./images/$uploadName1", "./images/$last_id".".".$ext1);
// GO BACK TO THREAD
header('Location: ./thread.php');
}
}
mysqli_close($link1);
?>
I'm wondering why others suggest you to use mysqli_insert_id() when you want to get the thread_id. As I know, mysqli_insert_id() will return you the successfully inserted id of the last mysql query.
But here, when I check your code, you are not creating the thread here. It's something that has been already created (earlier).
What you trying to accomplish is (As I understand), you want to store the 'thread_id' in your 'comment' table as a reference to which thread this comment was posted, right?
My suggestion is to use a hidden field in your comment form and pass the thread_id to the submit page.
Then you can retrieve 'thread_id' too, in the same way you get the replyNickname, replyComment etc.
And then, use that 'thread_id' inside your query.
Ex:
//when pressed submit
if (isset($_POST['replySubmit'])) {
//buton ve textarea def
$deger = $_POST ['replyComments'];
$deger2 = $_POST ['replyNickName'];
$deger3 = $_FILES ['replyUserFile']['name'];
// WANT TO DEFINE THREAD ID HERE
$thread_id = $_POST ['thread_id']; // Note this line
//deger4 = $_POST [];
// SEND TO DATABASE
$sql1 = "INSERT INTO newReply (COMMENT, NAME, IMAGENAME, THREAD_ID) VALUES ('$deger', '$deger2', '$deger3', '$thread_id')";
//connection check
if (!mysqli_query($link1, $sql1)) {
die('Error: ' . mysqli_error());
} else {
header('Location: ./thread.php');
}
}
I hope what I understood is right. This is just a rough idea, you can pass the thread_id in anyway you want. But I don't see any point of using mysqli_insert_id() here.
//If the previous request triggered an auto increment
if (mysqli_insert_id($link)<>'') {
//retrieves the last ID
$lastID = mysqli_insert_id($link);
//do something
}
else {
//do something else...
}
Be sure that you chose INNODB engine in order to be able to handle foreign keys
Assuming you're using MySQL:
PDO (where $pdoConn is your PDO connection):
$yourlastID = $pdoConn->lastInsertId();
mysqli:
$yourlastID = $mysqli->insert_id;
If you are using MSSQL, use SCOPE_IDENTITY(). Read http://www.codeproject.com/Articles/103610/Difference-between-IDENTITY-SCOPE-IDENTITY-IDENT-C
create PROCEDURE [dbo].[spInsertIntoThreads]
(
#THREAD_ID int OUTPUT,
#Column1 varchar(50) = NULL,
)
AS
BEGIN
SET NOCOUNT ON;
Insert Into Threads(Column1)
values(#Column1);
SET #THREAD_ID=SCOPE_IDENTITY();
END
Hope it helps. :)

How to detect whether users have accepted terms?

Basically I am writing a PHP and MYSQL script that will check whether a user has accepted the terms and conditions or not. In the databse every current user that has signed up is set to "unaccepted". When they log in the first page that they are directed to should have a scirpt on it that detects whether or not the status of the tos column in the users table is set to "accepted" or "unaccepted". If it is accepted they can continue, and if it is not they they will be forced to go to a page and accept them before they can continue to use the rest of my site. This is the code so far but it doesn't seem to be working. Any suggestions help.
<?php
$username=$_SESSION['username'];
$connect = mysql_connect('**', '**', '**', '**');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('**'))
{
die('Could not select database: ' . mysql_error());
}
$toschecker = mysql_query("SELECT `tos` FROM `users` WHERE `username` = '$username'");
if (!$toschecker)
{
die('Could not query:' . mysql_error());
}
mysql_close($connect);
$unaccepted='unaccepted';
if ($toschecker === $unaccepted)
{
header('Location: accepttos.php');
}
?>
For some reason this isn't directing them to the accepttos.php page. Thanks in advance.
Change MySQL to MySQLi. Explanations are in the comments.
<?php
$username = $_SESSION['username'];
$connect = mysqli_connect('Host', 'Username', 'Password', 'Database');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
$toschecker = mysqli_query($connect,"SELECT `tos` FROM `users` WHERE `username` = '$username'"); /* SELECT TOS COLUMN */
while ($row = mysqli_fetch_array($toschecker))
{
$tos = $row['tos']; /* STORE TO A VARIABLE THE FETCHED TOS */
}
$unaccepted = 'unaccepted';
if ($tos == $unaccepted) /* COMPARE THE TOS VARIABLE IF UNACCEPTED */
{
header('Location: accepttos.php');
}
else {
header('Location: acceptedTOS.php'); /* IF TOS IS ACCEPTED. CHANGE THE LOCATION */
}
mysqli_close($connect);
?>
$toschecker is a resource , try the following under the mysql_query line to see the result of your query, which you can use to redirect accepttos.php etc..
if( $row = mysql_fetch_assoc($toschecker)) {
var_export($row['tos']);
}
You need to access the information in the fields of your database. Here is an example.
$toschecker = mysql_query($sql);
$row = mysql_fetch_array($toschecker);
$tos = $row['tos'];
if($tos == 'accepted'){
// go to regular page
}else {
// go to accept terms page
}

Inserting a null value into SQL if form field blank

I'm trying to add a null value into a database if the form field is left blank but not getting much luck...
Can anyone see where this is going wrong??
<?php
$con = mysql_connect("ipaddress","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
if (is_null($_POST["event_sub"]) || $_POST["event_sub"]=="") {
$event_sub = NULL;
} else {
$event_sub = mysql_real_escape_string($_POST["event_sub"]);
}
$sql="INSERT INTO myTable (event_sub)
VALUES
(". $event_sub .")";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
mysql_close($con)
?>
Perhaps try this:
if (is_null($_POST["event_sub"]) || $_POST["event_sub"]=="") {
$event_sub = 'NULL';
} else {
$event_sub = mysql_real_escape_string($_POST["event_sub"]);
}
Putting the NULL in single quotes will result in the word NULL being inserted into your query rather than an actual NULL, which is nothing.
why would you need to search for the word NULL? Just leave the insert for that column blank. and make sure allow null is set in the table..

Refresh PHP page once only when called

I have a php which would check for certain value if it exists in a mysql database. If the value does not exists, it would simply add the value and refresh the page once to load the page again and now it has a value in the database, would go ahead to add other values. How do I refresh page just once when it is called ?
<?php
$sname = "W3 schools C# tutorials";//$_POST["sitename"];
$stype = "C#";//$_POST["sitetype"];
$saddy = "www.w3schools.com";//$_POST["siteaddress"];
$scomm = "W3 schools C# tutorials";//$_POST["sitecomment"];
$conn = mysql_connect("localhost","root","password");
if(!$conn){
die("Could not connect: ".mysql_error());
} else {
mysql_select_db("bookmarks",$conn);
$rs = mysql_query("select TypeId from bookmarktypes where TypeName = '$stype'");
$row = mysql_fetch_array($rs);
if($row > 0 ){
//Data found, continue to add...
} else {
//No data... insert a valid one
$rs = mysql_query("insert into bookmarktypes (TypeName) values ('$stype')");
if (!$rs){
die('Error: ' . mysql_error());
} else {
//echo "inserted new type data...";
}
//echo "</html>";
}
}
mysql_close($conn);
//Refresh page once
?>
There's the comment to refresh page below after mysql close command.
Refresh it right after insert with
header('Location: url here');
exit;
Btw, read a little about sql injections
Also - mysql_close() is pointless there.
if(check=1)
{
echo "\"<meta http-equiv=\"refresh\" content=\"2;url=http://yourwebsite.com/\">\"\n";
}
if you need to print the data that you just have entered try this
header('Location: YourShowDataPage.php?id='.$_POST['id_dataEntered'])
mi apologizes if is wrong , im a begginer

Categories