This question already has answers here:
Warning: preg_replace(): Unknown modifier
(3 answers)
Closed 7 years ago.
I'm sure I'm just doing something stupid but I think I'm close. What I'm trying to do as add validation to my submission. With my current code regardless of what data I enter into the serial field it always comes up with Invalid Serial. Any suggestions?
<?php
$serial=$_POST['serial'];
$model=$_POST['model'];
$deviceCondition=$_POST['deviceCondition'];
$sealCondition=$_POST['sealCondition'];
$location=$_POST['location'];
$deployDate=$_POST['deployDate'];
$weight=$_POST['weight'];
$connectedTerminal=$_POST['connectedTerminal'];
$notes=$_POST['notes'];
//NEW PDO connection
$serialVal = "[a-zA-Z0-9-]+";
if ( preg_match( $serialVal, $serial ) ) {
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "INSERT INTO web01dev4s2.ingenicoInfo (serial, model, deviceCondition, sealCondition, location, deployDate, weight, connectedTerminal, notes) VALUES ('".$serial."', '".$model."', '".$deviceCondition."', '".$sealCondition."', '".$location."', '".$deployDate."', '".$weight."', '".$connectedTerminal."', '".$notes."')";
$q = $conn->prepare($sql);
$result_1=($sql);
$q->execute();
}
catch (PDOException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
$count = $q->rowCount();
print("Saved $count record(s).\n");
header( "refresh:2;url=devicelist.php" );
}
else {
echo $serial . "Invalid serial number.";
}
?>
You forgot the delimiters "/"
if(preg_match("/[a-zA-Z0-9-]+/", $serial))
echo 'oui';
else
echo 'no';
Related
This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How can I prevent SQL injection in PHP?
(27 answers)
Closed 3 years ago.
I'm trying to insert data into the database, it run my coding and i get output as 'SOP data Added Successfully', but the data does not get into the database.
if (isset($_SESSION['admin_id']))
{
include 'databaseConnection.php';
if (isset($_POST['add_btn']))
{
$sop_name = $_POST['sop_name'];
$sop_step = $_POST['sop_step'];
$sop_comment = $_POST['sop_comment'];
$department_id = $_POST['department_id'];
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM sop WHERE sop_name = '$sop_name' && admin_id = '".$_SESSION['admin_id']."'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
if ($count == 1)
{
echo '<script language="javascript">';
echo 'alert("SOP Data Already Existed")';
echo '</script>';
}
else
{
$addSOP = "INSERT INTO sop(sop_name, sop_step, sop_comment, department_id, admin_id) VALUES('$sop_name' , '$sop_step' , '$sop_comment' , '$department_id' ,'$admin_id')";
mysqli_query($connection, $addSOP);
echo '<script language="javascript">';
echo "alert('SOP Data Added Succesfully'); window.location.href='dashboardOrganizationDepartment.php'";
echo '</script>';
}
}
?>
I expect that the result can be post into the database, but it is not. There is also not showing any errors for me to refer.
Can you put some try catch within your insert query, you will get the actual error in query
try {
$addSOP = "INSERT INTO sop(sop_name, sop_step, sop_comment, department_id, admin_id) VALUES('$sop_name' , '$sop_step' , '$sop_comment' , '$department_id' ,'$admin_id')";
mysqli_query($connection, $addSOP);
} catch (Exception $e) {
die($e->getMessage());
}
I am getting error
Undefined variable: company_name.
but some fields are inserted in database.
<?php
$con=mysqli_connect("localhost","root","","vdl");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$Company_name = $_POST['company_name'];
$since = $_POST['since'];
$strength = $_POST['strength'];
$head_quarter = $_POST['head_quarter'];
if($company_name !=''||$since !=''){
mysqli_query($con,"insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
mysqli_close($con);
}
else{
echo "<p>Insertion Failed <br/> Some Fields are Blank....!!</p>";
}
}
?>
First of all, mysql_* functions are deprecated as of PHP 5.5, and have been completely removed as of PHP 7.0.
Staying up to date with whats new and good now you reguarly want to update things aswell as PHP. Knowing that the mysql_* functions are deprecated (not under active development) we should not use them anymore (we can't even use them anymore if you have updated your php). Anyways back to the point you should not use mysql_* functions especially not now you are new to programming because you will have to update your php someday meaning you will have to change all of your code.
As of the code below:
This is mysqli_* mysqli.php
I have added a check on the db connection checking if that is actually working since you did not check the connection. Because even without that connection working that if loop would still return you your echo.
In mysqli_* you also have to add the connection in the query string.
<?php
$con=mysqli_connect("localhost","root","","vd1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$company_name = $_POST['company_name'];
$since = $_POST['since'];
$strength = $_POST['strength'];
$head_quarter = $_POST['head_quarter'];
if($company_name !=''||$since !=''){
mysqli_query($con,"insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
mysqli_close($con);
}
}
?>
First of all mysql is deprecated. Don't use mysql. Use either mysqli or pdo.
In your given code,
Add condition after $query statement to get exact error.
if (!$query) {
$message = 'Invalid query: ' . mysql_error() . "\n";
die($message);
}
else {
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
}
You should trace all errors that may occur. I suggest to use prepared statement, try this:
<?php
$sql = new mysqli("localhost", "root", "", "vdl");
if($sql->connect_errno)
return printf("MySQL Connection Error #%d: %s", $sql->connect_errno, $sql->connect_error);
// I'd recommend to not use $_POST['submit'], it'd be better to check all the fields (company_name, since, strength, head_quarter) using the strlen() function
// for example: if(strlen($company = $_POST["company_name"]) && strlen($since = $_POST["since"])) ... etc.
if(isset($_POST["submit"]))
{
if(!$sm = $sql->prepare("INSERT INTO `digital_library` (`company_name`, `since`, `strength`, `head_quarter`) VALUES (?, ?, ?, ?)"))
return printf("Unable to prepare statement. Error #%d: %s", $sm->errno, $sm->error);
if(!$sm->bind("ssss", $_POST["company_name"], $_POST["since"], $_POST["strength"], $_POST["head_quarter"]))
return printf("Unable to bind parameters. Error #%d: %s", $sm->errno, $sm->error);
if(!$sm->execute())
return printf("MySQL Query Error #%d: %s", $sm->errno, $sm->error);
printf("The query has successfully executed!");
} else
printf("There's nothing to see, get outta here");
?>
If you don't want to use prepared statement, do this:
<?php
$sql = new mysqli("localhost", "root", "", "vdl");
if($sql->connect_errno)
return printf("MySQL Connection Error #%d: %s", $sql->connect_errno, $sql->connect_error);
if(
strlen( $company = $sql->real_escape_string($_POST["company_name"]) )
&& strlen( $since = $sql->real_escape_string($_POST["since"]) )
&& strlen( $strength = $sql->real_escape_string($_POST["strength"]) )
&& strlen( $head_quarter = $sql->real_escape_string($_POST["head_quarter"]) )
) {
$query = sprintf("INSERT INTO `digital_library` (`company_name`, `since`, `strength`, `head_quarter`) VALUES ('%s', '%s', '%s', '%s')", $company, $since, $strength, $head_quarter);
if(!$q = $sql->query($query))
return printf("MySQL Query Error #%d: %s", $sql->errno, $sql->error);
printf("The query has successfully executed!");
} else
printf("There's nothing to see, get outta here");
?>
Do one thing and It will be easy for you to debug-
Change this
$query = mysql_query("insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')");
echo "<br/><br/><span>Data Inserted successfully...!!</span>";
to
echo "insert into digital_library(company_name, since, strength, head_quarter) values ('$company_name', '$since', '$strength', '$head_quarter')";
Now when you submit you get the original query in response.
Now run this query in phpmyadmin manually and see the results. Correct the issues phpmyadmin gives you and update your query in your script accordingly.
This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 4 years ago.
Here is my php and mysql code. It don't show any data . please tell me where is my error:
<?php
$ddaa = mysql_query("SELECT ref FROM users WHERE id='$uid'");
$mallu2 = mysql_query("SELECT mallu FROM users WHERE id='$ddaa'");
$result = mysql_fetch_array($mallu2);
echo $result['mallu'];
?>
You can use Mysqli,mysql is deprecated
a little example:
conection to db test
$mysqli = new mysqli('127.0.0.1', 'user', 'password', 'test');
if ($mysqli->connect_errno) {
echo "Error: Errot on connection : \n";
echo "Errno: " . $mysqli->connect_errno . "\n";
}
// the query
$sql = "SELECT ref FROM users WHERE id=$uid";
//if don't have result
if ($resultado->num_rows === 0) {
echo "we can't find data with $uid. try again !.";
exit;
}
//print the result
while ($dato = $resultado->fetch_assoc()) {
echo $dato['ref'];
}
Mysqli Php documentation
This question already has answers here:
Why does this PDO statement silently fail?
(2 answers)
Closed 5 years ago.
I am trying to insert into DB getting data from URL but doesn't work
here the link
http://localhost/test/recevier.php?heat1=33&heat2=33&heat3=33&gas=33&motion=33
here my db.php file
$dsn = "mysql:host=127.0.0.1;dbname=test;";
$user = 'root';
$pass = '';
try {
$conn = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'field to connect' . $e->getMessage();
}
and here my recevier.php file
include "db.php";
$heat1 = $_GET['heat1'];
$heat2 = $_GET['heat2'];
$heat3 = $_GET['heat3'];
$gas = $_GET['gas'];
$motion = $_GET['motion'];
$personId = 1;
echo $heat1;
echo $heat2;
echo $heat3;
echo $gas;
echo $motion;
$entryId = 3;
$vars = $conn->prepare("INSERT INTO var(entryId, heat1, heat2, heat3, gas, mation, personId) VALUES (:zentryId, :zheat1, :zheat2, :zheat3, :zgas, :zmotion, :zpersonId)");
$vars->bindParam(':zentryId', $entryId);
$vars->bindParam(':zheat1', $heat1);
$vars->bindParam(':zheat2', $heat2);
$vars->bindParam(':zheat3', $heat3);
$vars->bindParam(':zgas', $gas);
$vars->bindParam(':zmotion', $motion);
$vars->bindParam(':zpersonId', $personId);
$vars->execute();
and this is the table I am trying to insert into
the 'echo' statement to check if the file get the data & he git it
enter image description here
What does the error says? Anyway I notice there's a typo in this line:
$vars = $conn->prepare("INSERT INTO var(entryId, heat1, heat2, heat3, gas, mation,
Should it be :
$vars = $conn->prepare("INSERT INTO var(entryId, heat1, heat2, heat3, gas, motion, personId) VALUES (:zentryId, :zheat1, :zheat2, :zheat3, :zgas, :zmotion, :zpersonId)");
This question already has answers here:
Stop data inserting into a database twice
(16 answers)
Closed 8 years ago.
I have this code below and it works fine except when I refresh the page it inserts a blank row. Does anyone know what I need to do here?
<?php
$con=mysqli_connect("localhost","name","password","inventory");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$inv_number = mysqli_real_escape_string($con, $_POST['inv_number']);
$date = mysqli_real_escape_string($con, $_POST['date']);
$date_type = mysqli_real_escape_string($con, $_POST['date_type']);
$item1 = mysqli_real_escape_string($con, $_POST['item1']);
$location1 = mysqli_real_escape_string($con, $_POST['location1']);
$sql="INSERT INTO invoice (inv_number, date, date_type, item1, location1)
VALUES ('$inv_number', '$date', '$date_type', '$item1', '$location1')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo 'Invoice #'.$_POST['inv_number'].' recorded';
mysqli_close($con);
?>
I tried finding conditional if statements that can keep the code from creating blank rows but to no avail have I found a working solution.
Any help is appreciated.
<?php
$con=mysqli_connect("localhost","name","password","inventory");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (empty($_POST['inv_number']) || empty($_POST['date']) ||empty($_POST['date_type'])
|| empty($_POST['item1']) || empty($_POST['location1']))
{
echo "Re direct user by using header or show them messages";
}
else {
// set your variable and run your query
//i just copy and posted your code from your question
// escape variables for security
$inv_number = mysqli_real_escape_string($con, $_POST['inv_number']);
$date = mysqli_real_escape_string($con, $_POST['date']);
$date_type = mysqli_real_escape_string($con, $_POST['date_type']);
$item1 = mysqli_real_escape_string($con, $_POST['item1']);
$location1 = mysqli_real_escape_string($con, $_POST['location1']);
$sql="INSERT INTO invoice (inv_number, date, date_type, item1, location1)
VALUES ('$inv_number', '$date', '$date_type', '$item1', '$location1')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo 'Invoice #'.$_POST['inv_number'].' recorded';
}
mysqli_close($con);
?>
Important to note your query will not run, if any of the feild which is given in if statement are empty
Please read the comment in the solution