I am currently working on this project. Data can be retrieved from database with this code, if certificateNumber is numeric, but it does not search person if certificateNumber field has alphanumeric data.
Where am I wrong with this?
<?php
$flag = 0;
$reg=$_REQUEST["cerf"];
echo ($reg);
$con = mysqli_connect('localhost','neoncom_db','12345','neoncom_std');
$qur = 'select * from student where certificateNumber = '.$reg;
$check = mysqli_query($con,$qur);
while($row=mysqli_fetch_array($check))
{
if($reg==$row["certificateNumber"])
{
$flag++;
$first = $row["first"];
$last=$row["last"];
$num = $row["certificateNumber"];
$name = $first ." ".$last;
$course = $row["course"];
$date = $row["signupDate"];
echo($row["certificateNumber"]);
echo($row["first"]);
echo($row["last"]);
}
}
if(count==0)
{
echo("NOT FOUND");
}
?>
You need to encapsulate $reg in quotes. So your query string $qur should be like this:
$qur = "select * from student where certificateNumber = '" . $reg . "'";
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection attack. Also see how you can prevent SQL injection in PHP.
Related
I am trying to build a cart using MySQL. I keep getting this error 'Query was empty' when I run this code. Please help I've tried several things such as putting the variables inside the string instead of concatenating it.
<?php ob_start(); ?><?php require_once("../include/membersite_config.php"); ?>
<?php
require('../products_reloaded/config.php');
session_start();
$user = $_REQUEST['user'];
$user = mysql_real_escape_string($user);
$itemNum = $_REQUEST['itemNum'];
$itemNum = mysql_real_escape_string($itemNum);
$quantity = $_POST['quantity'];
$quantity = intval($quantity);
$CheckForExistence = mysql_query("select * from cart where user = '$user' and p_number = '$itemNum'" );
$alreadyExistsChecker = mysql_num_rows($CheckForExistence);
if($alreadyExistsChecker >= 1)
{
$quantity +=1;
echo "this is equal to $alreadyExistsChecker";
}
if($alreadyExistsChecker == 0)
{
$getQuery = mysql_query("select * from product where p_number = '$itemNum'");
while($row = mysql_fetch_array($getQuery))
{
$name = $row['p_name'];
$image = $row['p_url'];
$price = $row['p_price'];
}
$name = mysql_real_escape_string($name);
$image = mysql_real_escape_string($image);
$price = intval($price);
$query = mysql_query('insert into cart values('.$user.','.$itemNum.','.$name.', '.$image.','.$quantity.', '.$price.')');
$result = mysql_query($query);
if (!$result) {
print "An error occured: " . mysql_error() . "\n";
}
}
header('http://www.definitionxjm.com/shopping/viewCart.php');
?>
What do you try to achieve with this line?
$result = mysql_query($query);
Just delete it and change the line above to
$result = mysql_query('insert into cart values('.$user.','.$itemNum.','.$name.', '.$image.','.$quantity.', '.$price.')');
[Edit]
Btw. you are forgetting the " (quotes) inside the query which causes an sql error to occur, leading to $query = false (see manual). $query (false) then gets converted to string, resulting in '' (an empty string) which you pass to mysql_query and that generates an "Query was empty"-Message, as it should because you tried to send an empty query.
It can also mean the table which is in consideration is empty.This condition arises when the "DELETE FROM table_name where ;" is used. Here if the table "table_name" has no data, it cannot delete anything and hence it shows an error stating that the query is empty.
I am getting SQL & URL injection vulnerabilities when I scan my website. This is the code I'm using:
if(isset($_GET["id"]))
{
if(!is_int($_GET["id"]) ==FALSE)
{
//redirect this person back to homepage
} else {
$sql = "SELECT * FROM workshop WHERE id=".trim($_GET['id']);
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$id = $row['id'];
$prod_name = $row['prod_name'];
$description = $row['description'];
$image1 = $row['image1'];
$image2 = $row['image2'];
$image3 = $row['image3'];
$pdfFileName = $row['pdfFileName'];
$publish = $row['publish'];
$workshop_date = $row['workshop_date'];
$workshop_date_end = $row['workshop_date_end'];
$course_desc = $row['course_desc'];
$attend = $row['attend'];
$trainer_detail = $row['trainer_detail'];
$location = $row['location'];
$dateValue = $row['workshop_date'];
$year = date('Y',strtotime($dateValue));
$month = date('F',strtotime($dateValue));
$day = date('d',strtotime($dateValue));
$dateValue1 = $row['workshop_date_end'];
$year1 = date('Y',strtotime($dateValue1));
$month1 = date('F',strtotime($dateValue1));
$day1 = date('d',strtotime($dateValue1));
}
}
How do I fix it?
The SQL injection problem is in this row:
$sql = "SELECT * FROM workshop WHERE id=".trim($_GET['id']);
You're applying the value from get directly into your query without escaping it.
Do this instead:
$id = mysql_real_escape_string(trim($_GET['id']));
$sql = "SELECT * FROM workshop WHERE id=$id";
Remember that you're using deprecated mysql_* functions, mysqli_* should be used instead. Consider updating your code.
I want to add multiple data into table at once but my code gives an error saying 'cannot use string offset as an array'. I have attached my code. Can anyone help me to solve this?
$issuedate=$_POST['issuedate'];
$member=$_POST['member'];
$bno[0]['TitleNo'] = $_POST['bno'];
$bno[1]['TitleNo'] = $_POST['bno1'];
$bno[2]['TitleNo'] = $_POST['bno2'];
$bno[3]['TitleNo'] = $_POST['bno4'];
$returndate = $_POST['returndate'];
for($i=0; $i<4; $i++)
{
$sql5 = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES ('".$bno[$i]['TitleNo']."','$member','$issuedate','$returndate')");
}
if ($sql5)
{
echo '<h4 class="message">Add New Book Copies! </h4>'; // echo $test;
}
else
{
echo 'Fail.';
}
You are probably assigning string to $bno variable thus it dynamically becomes of type string. More info here. Regarding the example you should
$bno = array();
Escape all your DB inputs (or even better, use prepared statements)
It makes more sense to put the if..else inside the for loop
Thus
$bno = array();
$mysqli_conn = mysqli_connect("localhost", "user", "password", "schema");
$issuedate = mysqli_real_escape_string($mysqli_conn, $_POST['issuedate']);
$member = mysqli_real_escape_string($mysqli_conn, $_POST['member']);
$bno[0]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno']);
$bno[1]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno1']);
$bno[2]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno2']);
$bno[3]['TitleNo'] = mysqli_real_escape_string($mysqli_conn, $_POST['bno4']);
$returndate = mysqli_real_escape_string($mysqli_conn, $_POST['returndate']);
for($i=0; $i<4; $i++)
{
$sql = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES ('".$bno[$i]['TitleNo']."','".$member."','".$issuedate."','".$returndate."')");
if ($sql)
{
echo '<h4 class="message">Add New Book Copies! </h4>'; // echo $test;
}
else
{
echo 'Fail.';
}
}
You have set $bno as string in some previous code.
What you can do for a quick fix is:
change $bno to somehing else, for example $book
$book[0]['TitleNo'] = $_POST['bno'];
$book[1]['TitleNo'] = $_POST['bno1'];
//..
set $bno to a new array and then assign the values
$bno = array();
$bno[0]['TitleNo'] = $_POST['bno'];
$bno[1]['TitleNo'] = $_POST['bno1'];
//...
Additional Notes
By the way it's better to escape somehow the values you enter in your DB. You can use mysqli_real_escape_string
Just assign do this for all the values:
$bno[0]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno']);
Sources to read
http://php.net/manual/en/mysqli.real-escape-string.php
You should have a look att prepared statements and bind params. When you're doing the insert statements you select five columns and only inserts four values.
$sql5 = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES ('".$bno[$i]['TitleNo']."','$member','$issuedate','$returndate')");
And as #jeroen mentioned, your code has sql-injection problems, read more about sql-injection here.
I've created and exampel using prepared statements and bind params. Note:
$stmt->bind_param('sssss',$bno[$i]['TitleNo'], $member, $issuedate, $dueDate, $returndate);
'sssss' are just for demo purpose, I assume dueDate and returndate columns are datetime something simular.
$DBServer = 'localhost';
$DBUser = 'root';
$DBPass = 'root';
$DBName = 'borrow';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
$sql = ' INSERT INTO borrow (TitleNo,MemberID,IssueDate,dueDate,ReturnDate) VALUES (?,?,?,?,?)';
$TitleNo = $bno[0]['TitleNo'];
$member = 'MemberID';
$issuedate = 'issuedate';
$dueDate = 'dueDate';
$returndate = 'returndate';
/* Prepare statement */
$stmt = $conn->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
}
for( $i= 0; $i < count($bno); $i++){
/* Bind parameters. s = string, i = integer, d = double, b = blob */
$stmt->bind_param('sssss',$bno[$i]['TitleNo'], $member, $issuedate, $dueDate, $returndate);
/* Execute statement */
$stmt->execute();
}
if( $stmt->affected_rows > 0 ){
echo '<h4 class="message">Add New Book Copies!</h4>';
}
$stmt->close();
However im not sure if it's best practice to do a mass insert to db using a for-loop.
Initialising your array (ie, $bno was probably initialised to a string in your code which caused the error you are seeing), escaping the input and doing a single INSERT (rather than 4, where you only check the results of the last one):-
<?php
$bno = array();
$sql_array = array();
$issuedate = mysqli_real_escape_string($db, $_POST['issuedate']);
$member = mysqli_real_escape_string($db, $_POST['member']);
$bno[0]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno']);
$bno[1]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno1']);
$bno[2]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno2']);
$bno[3]['TitleNo'] = mysqli_real_escape_string($db, $_POST['bno4']);
$returndate = mysqli_real_escape_string($db, $_POST['returndate']);
foreach($bno AS $abno)
{
$sql_array = "('".$bno['TitleNo']."','$member','$issuedate','$returndate')"
}
$sql5 = mysqli_query($db, "INSERT INTO borrow(TitleNo,MemberID,IssueDate,dueDate,ReturnDate)
VALUES ".implode(', ', $sql_array));
if ($sql5)
{
echo '<h4 class="message">Add New Book Copies!</h4>';
// echo $test;
}
else
{
echo 'Fail.';
}
This does suggest that the database could be further normalised, as you have multiple rows being inserted that are identical except for one value.
I am trying to build a cart using MySQL. I keep getting this error 'Query was empty' when I run this code. Please help I've tried several things such as putting the variables inside the string instead of concatenating it.
<?php ob_start(); ?><?php require_once("../include/membersite_config.php"); ?>
<?php
require('../products_reloaded/config.php');
session_start();
$user = $_REQUEST['user'];
$user = mysql_real_escape_string($user);
$itemNum = $_REQUEST['itemNum'];
$itemNum = mysql_real_escape_string($itemNum);
$quantity = $_POST['quantity'];
$quantity = intval($quantity);
$CheckForExistence = mysql_query("select * from cart where user = '$user' and p_number = '$itemNum'" );
$alreadyExistsChecker = mysql_num_rows($CheckForExistence);
if($alreadyExistsChecker >= 1)
{
$quantity +=1;
echo "this is equal to $alreadyExistsChecker";
}
if($alreadyExistsChecker == 0)
{
$getQuery = mysql_query("select * from product where p_number = '$itemNum'");
while($row = mysql_fetch_array($getQuery))
{
$name = $row['p_name'];
$image = $row['p_url'];
$price = $row['p_price'];
}
$name = mysql_real_escape_string($name);
$image = mysql_real_escape_string($image);
$price = intval($price);
$query = mysql_query('insert into cart values('.$user.','.$itemNum.','.$name.', '.$image.','.$quantity.', '.$price.')');
$result = mysql_query($query);
if (!$result) {
print "An error occured: " . mysql_error() . "\n";
}
}
header('http://www.definitionxjm.com/shopping/viewCart.php');
?>
What do you try to achieve with this line?
$result = mysql_query($query);
Just delete it and change the line above to
$result = mysql_query('insert into cart values('.$user.','.$itemNum.','.$name.', '.$image.','.$quantity.', '.$price.')');
[Edit]
Btw. you are forgetting the " (quotes) inside the query which causes an sql error to occur, leading to $query = false (see manual). $query (false) then gets converted to string, resulting in '' (an empty string) which you pass to mysql_query and that generates an "Query was empty"-Message, as it should because you tried to send an empty query.
It can also mean the table which is in consideration is empty.This condition arises when the "DELETE FROM table_name where ;" is used. Here if the table "table_name" has no data, it cannot delete anything and hence it shows an error stating that the query is empty.
need help inputs are not inserted to db when there is an apostrophe in the textfield values, im trying to use the codes below to escape the ' but its not working,
function myaddslashes($string){
if(get_magic_quotes_gpc() == 1){
return $string;
} else {
return str_replace("'", "''", $string);
}
}
ive used this as well to no avail:
function check_input($value)
{
// Stripslashes
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote if not a number
if (!is_numeric($value))
{
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
here is my php code:
<?php
error_reporting(0);
require 'include/DB_Open.php';
$RemedyTicketNo = $_POST['RemedyTicketNo'];
$PhoneNumber = $_POST['PhoneNumber'];
$Category2 = $_POST['Category2'];
$Category3 = $_POST['Category3'];
$Status = $_POST['Status'];
$Createdate = $_POST['Createdate'];
$Date = $_POST['Date'];
$Severity = $_POST['Severity'];
$BanType = $_POST['BanType'];
$XiD = $_POST['XiD'];
$Ticket = $_POST['Ticket'];
if (isset($RemedyTicketNo))
{
$sql="INSERT into tbl_main (ars_no, phone_number, category_1, category_2, status, create_date, resolved_date, trouble_type_priority, ban_type, employee_id_name)
VALUES ('".$RemedyTicketNo."', '".$PhoneNumber."', '".$Category2."', '".$Category3."', '".$Status."', '".$Createdate."', '".$Date."', '".$Severity."', '".$BanType."', '".$XiD."')";
$result=mysql_query($sql);
header("Location: wireless_new.php");
}
?>
P.S...im new to php and sql so im still trying to learn to use sqli...
All strings should be escaped using a database-specific function. In your case mysql_real_escape_string
If you're learning, you're better off starting with MySQLi as the MySQL extension is deprecated as of PHP 5.5.0. It's no more difficult than the one you're using.
Use query parameters or whatever the php equivalent is called. Escaping quotes is one of the good things they do for you.
Mysqli will happily accept a single quote if it gets properly escaped.
but for some reason you don't actually apply none of your functions to the input. So, that's the only your problem.
Also note that error_reporting should always be E_ALL, not 0
i was able to fixed it by adding mysql_real_escape_string the field which has ' value
$RemedyTicketNo = $_POST['RemedyTicketNo'];
$PhoneNumber = $_POST['PhoneNumber'];
$Category2 = $_POST['Category2'];
$Category3 = **mysql_real_escape_string** ($_POST['Category3']);
$Status = $_POST['Status'];
$Createdate = $_POST['Createdate'];
$Date = $_POST['Date'];
$Severity = $_POST['Severity'];
$BanType = $_POST['BanType'];
$XiD = $_POST['XiD'];
$Ticket = $_POST['Ticket'];
if you are using
(all book's are available) as $subject and you are trying to insert in to mysql
use this
$subject=$_POST['subject'];
$disc_str = addslashes($subject);
"INSERT INTO table name (subject) value('$disc_str')";
it works for me in Textarea with tinymce also