how to catch error code in PHP - php

i want to add records to table 'pool' with attribute ID and empName from database employees
theform.html
<FORM NAME ='form2' METHOD ='POST' ACTION ='result.php' enctype="multipart/form-data">
<B>Board Write</B> <BR>
<INPUT TYPE = Text Name = empID value = 'write ID here'>
<INPUT TYPE = Text Name = empName VALUE = 'write name here'><P>
<INPUT TYPE = 'Submit' Name = Submit2 VALUE = 'Post'>
</FORM>
result.php
<?PHP
$ID = $_POST['empID'];
$NAME = "'" . $_POST['empName'] . "'";
$server = "127.0.0.1"; //connect to server
$user_name = "root";
$password = "";
$database = "employees";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if($db_found){// there is a database
$tableSQL = "INSERT INTO pool(ID, empName) VALUES " . "(" . $ID . "," . $NAME . ")";
$result = mysql_query($tableSQL);
if($result){
print "success!";
}
else{
print "fail!";
}
}
mysql_close($db_handle); //close the connection;
?>
in the database, ID is unique and also an INT datatype, i want to catch the error code where the user inputs an ID value that already existing in the database. how do we do this?

You can use mysql_errno() (or mysqli_errno(), if you use mysqli) to get the error number after a query if it failed (check the return value of mysql_query()). It should be error #1022 (ER_DUP_KEY) according to the mysql error documentation

In general, it is better to prevent SQL errors than to catch them. For example, check whether a duplicate exists before you even try to insert the record.
To avoid the issue altogether, you could use an auto-increment field for the ID, and allow the database to assign new numbers automatically. Then the user would never need to enter it, so there would never be a clash due to duplicates.
If you do still need to check for errors, then you can use the mysql_error() or mysql_errno() functions to get the error details.

// returns true if duplicated
function duplicate_catch_error ($database_connection) {
$mysql_error = array (1022 => "Can't write; duplicate key in table '%s'",1062 => "Duplicate entry '%s' for key %d", 1586 => "Duplicate entry '%s' for key '%s'"); // also allows for the use of sscanf
if (array_key_exists(mysql_error($database_connection),$mysql_error)) // checks if error is in array
return true;
else
return false;
}
hope this answers your question, also mysql is now depreciated. Use mysqli if you didn't already know
:)

Related

How to store data into multiple MySQL tables according to the checkbox value?

I have an html form, with multiple checkboxes (subjects)
When a user (student) selects the subjects ,the StudentID is stored in a MySQL table along with the selections made in separate columns but in the same table.
My question is: How can I store the student ID in a new table if the checkbox value "equals" to something, would strpos do it ?
for example:
if (strpos($cc,'252000') !== false) {
mysqli_query($dbcon,"INSERT INTO newtable (studentid,ckb)
VALUES ('$studentid','$cc')");
}
Full Code:
<?php
$host = 'localhost';
$port = 8889;
$username="root" ;
$password="root" ;
$db_name="db1" ;
$tbl_name="courses" ;
$tbl_name="studentinfo";
$tbl_name="newtable";
$dbcon = mysqli_connect("$host","$username","$password","$db_name") ;
mysqli_set_charset($dbcon, "utf8");
if (!$dbcon) {
die('error connecting to database'); }
$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']); //echo $studentid;
$name = $_GET['ckb'];
if(isset($_GET['ckb']))
{
foreach ($name as $courses){
$cc=$cc. $courses.',';
}
}
if (strpos($cc,'252000') !== false) {
mysqli_query($dbcon,"INSERT INTO newtable (studentid,ckb)
VALUES ('$studentid','$cc')");
echo "$cc, trtue";
}
HTML
<form action="cdb.php" method="get">
<input name="studentid" type="text" id="studentid" maxlength="11"value="Student ID" />
<input type="checkbox" name="ckb[]" value="251000-1"/>
<input type="checkbox" name="ckb[]" value="251000-2"/>
Ok if you absolutely must ignore all good database design practices try this.
Instead of creating a comma delimited list and putting it into the newtable use the serialize() function to place the contents of $_GET['ckb'] into this new row. At least this way you can use unserialize() to get back an array which makes manipulating the data easier even if it does not make searching the database any easier.
You could replace serialise/unserialize with json_encode() and json_decode()
references:
serialize: http://php.net/manual/en/function.serialize.php
unserialize: http://php.net/manual/en/function.unserialize.php
<?php
$host = 'localhost';
// I assume you moved apache to port 8889.
// so its irrelevant to mysql connection,
// good job you are not actually using this variable anywhere
$port = 8889;
$username="root" ;
$password="root" ;
$db_name="db1" ;
// fix so you have 3 variables and are not overwriting the same one
$tbl_name1="courses" ;
$tbl_name2="studentinfo";
$tbl_name3="newtable";
// remove unnecessary double quotes
$dbcon = mysqli_connect($host,$username,$password,$db_name) ;
// add some error checking that reports the actual error
if ( ! $dbcon ) {
echo 'Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error();
exit;
}
mysqli_set_charset($dbcon, "utf8");
if(isset($_GET['ckb'])) {
$studentid = mysqli_real_escape_string($dbcon, $_GET['studentid']);
$cc = serialize($_GET['ckb']);
$result = mysqli_query($dbcon,"INSERT INTO newtable
(studentid,ckb)
VALUES ('$studentid','$cc')");
if ( ! $result ) {
echo mysqli_error($dbcon);
exit;
}
}
?>
Below, total size of 'ckb' checkbox is calculated. Then. due to for loop, it will run till the total size. 'studentid' coming from the textbox. It will insert into the table till for loop condition is true.
extract($_POST);
$CKBsize=sizeof($ckb);
for($i=0;$i<$CKBsize;$i++)
{
$CourseName=$ckb[$i];
mysql_query("INSERT INTO newtable SET studentid='$studentid', ckb='$CourseName'");
}
It turns out , that using this code does in fact sort the data according to the checkbox in new and different tables
if (strpos($cc,'251000') !== false) {
$sql3="INSERT INTO newtable (studentid, ckb)
VALUES ('$studentid', '$cc')";
echo 'true';
}
However It seems I must check for the sql3 statement
if (!mysqli_query($dbcon,$sql3))
{
die('Error: ' . mysqli_error($dbcon));
}
Another mistake I had was using reserved words such as table in one of the sql statements. that fixed and the code above added solved the problem.

deleting the displayed key from database in php

so i have this key giveaway script, now i want to get the displayed key deleted from the database. how do i get this to work within the code i wrote?
so $key is the key that will be send to you and display in the browser, but i want this key to get deleted out of the database after it is send and displayed so it cannot get shown a second time to another user.
<?php
//fill in mail
echo "
<form method='post' action=" . $_SERVER['PHP_SELF'] . ">
Email: <input name='email'></input><br>
<input type='submit' value='Get your key' name='submit'> </input><br><br>
</form>";
if(empty($_POST["email"]))
{
echo "Please enter an email adress.";
}
else{
// get key from database
$key = dispres();
//mail key to input mail
$to = $_POST["email"];
$subject = 'Your test key';
$message = 'Your key is: ' . $key;
$headers = 'There you go!';
mail($to, $subject, $message, $headers);
echo "Your code has been sent to your email: " . $_POST["email"] . " \r";
echo $key;
}
function dispres(){
//database connect
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'pwd';
$database = 'c3keys';
$table = 'test';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
//grab random key from database
$result = mysql_query("SELECT * FROM {$table} order by RAND() LIMIT 1");
$row = mysql_fetch_row($result);
$result = implode('|',$row);
return $result;
//delete key from database
//had this as a begin
mysqli_query("DELETE FROM test WHERE test='$key'");
//remember ip adress for 1 use only
}
?>
1- you're using both mysql and mysqli stick with one...
2- your delete query is after the return so it will never run.
3- what is $key? I don't see where you set it.
4- STOP USING mysql_* these functions are deprecated. Use mysqli or PDO with prepared statements.
Explanation point 1:
In your code at the beginning of your dispres function, you have mysql_connect, mysql_select_db and mysql_query at the end for your delete query you used mysqli_query notice the i in the last function, you can't use mysqli here, as you had connected with mysql adapter.
Explanation point 2:
You have return $result; then after that you have mysqli_query("..."); PHP won't execute that line of code because for PHP and any other programming language when they see a return this means the function is done, nothing more to do, so you can't have any line that you want executed after the return
Explanation point 3:
In your whole dispres function there isn't $key so basically $key is empty, I think you mean using $result in that query. And even if you use $result your delete won't work, because $result is a string where you joined all your fields into it and added | pipe sign between each one and the other. so column test will never be equal to your $result. You should replace $key by the actual value of the test column you want to delete maybe like this:
$row = mysql_fetch_row($result);
$test_i_want_to_delete=$row[0];//Where 0 is the number of column of `test` in your db table, starting counting from 0
$result = implode('|',$row);
mysql_query("DELETE FROM test WHERE test='$test_i_want_to_delete'");
Explanation point 4:
If you're just starting to learn PHP it would be much better for you not to learn any deprecated functions that will be totally removed in future releases. So at the place of using mysql_* functions, take a look at PDO or mysqli, and especially look at how to use prepared statements.
I hope my answer helps clear out some stuff.

Beginner MySQL database search - not getting results

I am having my first attempts to a search engine:
I have a database called "global" and a table called "mpl" which contains 11 columns (Named: Customer, Part No, Descripton, Country Of Origin, and several other) with multiple rows for parts.
What i aim to do with the code below - is to get the Description and Country Of Origin displayed for the Part No the user has entered to the search field.
Form:
<form action="search.php" method="post">
<input type="text" name="find" /><br />
<input type="submit" value="Search" /> </form>
And the PHP:
$host = "localhost";
$dbuser = "root";
$dbpass = " ";
$db = "global";
$con = mysql_connect($host, $dbuser, $dbpass);
if(!$con){ die(mysql_error());
}
$select = mysql_select_db($db, $con);
if(!$select){ die(mysql_error());
}
$item = $_REQUEST['find'];
$data = mysql_query("SELECT * FROM mpl WHERE 'Part No' ='".$item."'");
while($row = mysql_fetch_array($data)){
echo $row['Description']. "<br>";
echo $row['Country Of Origin']. "<br><p>";
}
?>
Can someone tell me what am i doing wrong? Once i enter anything to my form 'find' - i get no results. If i run the search using LIKE instead of "=" with no value - it displays a bunch of Descriptions and Country of origin - this means i have connected to my DB correctly. This is driving me nuts..I feel i have messed up the mysql_query() part somehow - but i can't figure out which part.
You are using the wrong characters to escape the Part No column name in your query. Escape them with the backticks (`) and it should be fine.
$data = mysql_query("SELECT * FROM mpl WHERE `Part No` ='".$item."'");
Also, you should validate the user's query to prevent SQL injection.
A lot of people here have already pointed out possible and actual errors in your code, but here's the combined solution. Firstly I converted your code to mysqli which is the correct way of connecting to a mySQL database. The way you were connecting is out of date, and not recommended. Secondly I added some code to stop sql injection. Thirdly, I changed 'Part No' to `Part No``(ignore the second back tick) in your query.
<?php
$mysqli = new mysqli('localhost', 'root', DB_PASSWORD, 'global');
/* check connection */
if ($mysqli->connect_error)
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
/* escape string from sql injection */
$item = $mysqli->real_escape_string($_POST['find']);
/* query database */
$result = $mysqli->query("SELECT * FROM `mpl` WHERE `Part No` = '".$item."'");
while ($col = $result->fetch_array(MYSQLI_ASSOC))
echo '<p>' . $col['Description'] . '<br />' . $col['Country Of Origin'] . '</p>';
$result->close();
/* don't forget to close the connection */
$mysqli->close();
?>
What if you change:
$item = $_REQUEST['find'];
to
$item = $_POST['find'];
Also some function like mysql_select_db() are deprecated and going to be removed. See:
http://php.net/manual/en/function.mysql-select-db.php
Try changing this potion.
$item = $_REQUEST['find']; $data = mysql_query("SELECT * FROM mpl WHERE 'Part No' ='".$item."'");
to this
$item = $_POST['find'];
$data = mysql_query("SELECT * FROM mpl WHERE Part No ='$item'");
do something like this in your request to remove any possible whitespaces and normalize to upper case for select string.
$item = strtoupper(trim($_REQUEST['find']));
And do this in your SQL: to normalize as well.
$data = mysql_query("SELECT * FROM mpl WHERE UPPER(TRIM('Part No')) ='".$item."'");
You are basically not getting an exact match on your where clause
First off, I agree with Quentin; you should be using a database API like PDO or Mysqli. Secondly, it looks like people can search for parts by their part numbers or descriptions. Assuming the part numbers are numeric and the descriptions are strings... check the type of input and run the query accordingly.
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "global";
// Establish a database connection and select one.
// Try using one of the database API's.
// Then compose your sql by checking for the type of input from the form.
// Since your request method is a POST, then just look in the `_POST` superglobal.
$item = $_POST['find'];
if( is_numeric($item) ){
$sql = "SELECT * FROM mpl WHERE 'Part No' = {$item}";
}else{
$sql = "SELECT * FROM mpl WHERE 'Description' LIKE '%{$item}%'";
}
// Then perform the query.

Retrieving row from MySQL Database via PHP

Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);

Default Field Value to MySQL Database

I'm using a HTML form that captures user input for several fields, some of which can be left blank by the user, one particular field is called 'pasref'. What I would like to be able to do, if at all possible, is if this field is left blank by the user, for the default value to become the text 'Not Allocated' and for this to be saved as part of the record to a mySQL database.
I just admit I'm fairly new to this type of programming and I'm not sure whether this can be done within the mySQL database or whether it needs to be done as part of the php script that saves each record. I just wondered whether it would be at all possible please that someone could show me what I need to do?
I've included my PHP script below if it helps.
<?php
require("phpfile.php");
// Gets data from URL parameters
$userid = $_GET['userid'];
$locationid = $_GET['locationid'];
$pasref = $_GET['pasref'];
$additionalcomments = $_GET['additionalcomments'];
// Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = sprintf("INSERT INTO finds " .
" (userid, locationid, pasref, additionalcomments ) " .
" VALUES ('%s', '%s', '%s', '%s');",
mysql_real_escape_string($userid),
mysql_real_escape_string($locationid),
mysql_real_escape_string($pasref),
mysql_real_escape_string($additionalcomments));
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
You can set the default value on the column of mysql. You need to execute a query something like this:
ALTER TABLE finds MODIFY pasref varchar(100) default 'Not Allocated';
Change varchar(100) to whatever length it should be for your field.
Alternatively you could just set it in php:
if( empty($_GET['pasref']) ) {
$pasref = 'Not Allocated';
}
else {
$pasref = $_GET['pasref'];
}
Or finally you could put it as a default value in your form. Though the user would need to clear it if they want something else:
<input type="text" name="pasref" value="Not Allocated" />
Finally just to note in your PHP you need to escape your inputs to the database with mysql_real_escape_string or use PDO with placeholders. As is you have a SQL injection vulnerability.
It's also better to use POST. Change the form method to POST in your HTML and reference $_POST instead of $_GET
This can be solved by changing the column properties in the mysql database and setting the pasref column to not null and setting a default value.
Easily done if you can access the db using phpmyadmin
ALTER TABLE finds ALTER pasref SET DEFAULT = 'Not Allocated'
So when a new row is inserted with no value for column_name, Not Allocated with be used. It can also be done pretty easily with an interface like phpMyAdmin or MySQL Workbench if you have access to those tools.
Now all you have to do is check if pasref is empty in your PHP code and make sure you don't insert anything (an empty string "" is something) when it is the case.
you can just change the line
$pasref = $_GET['pasref'];
to
$pasref = $_GET['pasref'] == '' ? 'Not Allocated' : $_GET['pasref'];
Use this:
$query = " UPDATE $tabla SET fecha_ultimo_cambio=DEFAULT WHERE id in ($id) ";

Categories