I am inserting multiple rows from one submit button by the usage of array. Insertion of records is working smoothly. Now I want to stop insertion of data if record is already existed. My syntax for single record updating is works to prevent multi-insertion of same record. But I am confused and can't get idea while using array. I've tried a lot, but every method display error.
This code is working.
if(isset($_POST['submit'])){
$number = $_POST['number'];
$letter = $_POST['letter'];
$sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
$query = $con->prepare($sql);
foreach($number AS $key => $n){
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
}
}
My intention is to stop insertion of data if it is already inserted. So I tried like this. I am sure it is wrong because array variable can't pass to first syntax**(sql1)** and $query is not being accessed to foreach clause. I have no idea, So I used like this. Please provide me any idea to stop already inserted record.
I want to change in this code
<?php
if(isset($_POST['submit'])){
$number = $_POST['number'];
$letter = $_POST['letter'];
$sql1 = 'SELECT COUNT(*) FROM class WHERE number = :number';
$stmt = $con->prepare($sql1);
$stmt->bindParam(':number', $number[$key]);
$stmt->execute();
if($stmt->fetchColumn()){
echo"<script>alert('Class is already existed')</script>";
}
else{
$sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
$query = $con->prepare($sql);
}
foreach($number AS $key => $n){
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
}
}
?>
This code displays following error
Notice: Undefined variable: key in C:\xampp\htdocs\marksheet\class.php on line 53
Notice: Undefined variable: query in C:\xampp\htdocs\marksheet\class.php on line 57
Fatal error: Uncaught Error: Call to a member function bindParam() on null in C:\xampp\htdocs\marksheet\class.php:57 Stack trace: #0 {main} thrown in C:\xampp\htdocs\marksheet\class.php on line 57
This should work:
if (isset($_POST['submit'])) {
if(!empty($_POST['number']) && !empty($_POST['letter']) )
{
$number = $_POST['number'];
$letter = $_POST['letter'];
// Assuming both $number and $letter 1 dimensional array with equal number of indexes
$notInsertedKey = [];
foreach ($number AS $key => $item) {
/* Checking Existence*/
$sql1 = 'SELECT COUNT(*) as counted FROM class WHERE number = :number';
$stmt = $con->prepare($sql1);
$stmt->bindParam(':number', $number[$key]);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
if ($data['counted'] < 1) {
// echo "Not Exist";
$sql = "INSERT INTO class(number, letter) VALUES (:number, :letter)";
$query = $con->prepare($sql);
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
} else {
$notInsertedKey[] = $key;
// Incase you want to know the failed indexes.
echo "<script>alert('Class is already existed')</script>";
}
}
}
}
UPDATE
Solution suggested by #AlivetoDie works well as shorthand way to insert unique data and drop the duplicated one. However, it doesn't have any means to track the failed data indexes since the query always returns TRUE.
I would like to recommend following way. First of all you need a dynamic function which should check record in the relevant table
function isExist($columnName, $columnValue, $tableName){
$columnName = (!empty($columnName)) ? $columnName : 'empty';
$columnValue = (!empty($columnValue)) ? $columnValue : 'empty';
$tableName = (!empty($tableName)) ? $tableName : 'empty';
$exist = 0;
if($columnName != 'empty' && $columnValue != 'empty' && $tableName != 'empty'){
$sql = "select * from `".$tableName."` where `".$columnName."` = '".$columnValue."'";
$isExist = mysqli_query($this->connection,$sql);
if(mysqli_num_rows($isExist) > 0){
$exist = 1;
}
}
return $exist;
}
Then use it in your function by following way
if(isset($_POST['submit'])){
$error = 0;
$response = array();
$number = $_POST['number'];
$letter = $_POST['letter'];
$number_name_exist = $this->isExist('number', $number, 'class');
if($number_name_exist == 1){
$error = 1;
$response['error'] = $number . ' is already exists';
}
if($error == 0){
$sql = "INSERT INTO class(number, letter) VALUES(:number, :letter)";
$query = $con->prepare($sql);
foreach($number AS $key => $n){
$query->bindParam(':number', $number[$key]);
$query->bindParam(':letter', $letter[$key]);
$query->execute();
}
}
}
In the above example you can see there $error variable and $response array which will be make your script more dynamic and you can prevent duplicate insertion and also you can check multiple columns.
Related
I am playing around with php but the script doesnt execute to the last point and with no error...
What i am trying to do is checking the input of the user and comparing it what is in db and then applying conditions. So i have 2 files. update.php and dash.php.
dash.php is my html form page and i included 'update.php' in it
In my update.php, i have these codes
me.php is my html form page and i included 'update.php' in it
In my update.php, i have these codes
<?php
error_reporting(E_ALL);
include_once('database.php');
if(isset($_POST['submit']))
{
$q = $_GET['q'];
$next = $q + 1;
if($q == 26)
{
echo '<h2>Weldone!!</h2>';
}
elseif($q <= 25){
$sql = "SELECT * FROM Students WHERE Email=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s',
$_SESSION['login']);
$stmt->execute();
$result = $stmt->get_result(); $row = $result->fetch_assoc();
$Mark = $row['Mark'];
$Correct = $Mark + 1;
$Fail = $Mark + 0;
$sqlb = "SELECT * FROM Answers WHERE qid = ?";
$stmtb = $conn->prepare($sqlb);
$stmtb->bind_param('s', $q);
$stmtb->execute();
$resultb = $stmtb->get_result();
$rowb = $resultb->fetch_assoc();
$Answer =
$rowb['Answer'];
$Pick = $_POST['ans'];
if($Pick == $Answer)
{
$sqld = "UPDATE Students SET Mark=? WHERE Email = ?";
$stmtd = $conn->prepare($sqld);
$stmtd->bind_param('ss', $Correct,$_SESSION['login']);
$stmtd->execute();
$resultd = $stmtd->get_result();
echo "correct" ;
}
}
else
{
echo "<script type='text/javascript'>document.location.href='dash.php?q='.$next.';</script>";
}
}//post submit
?>
The else statement doesnt run. so it keeps reloading the same page.
Also i want to ask why i keep getting the value of 2 for my $Correct variable stored on the database into column Mark for a single correct question instead of 1. What could be wrong?
Lastly, i dont want the script to run if the browser is edited by the user by changing the value of $q from the browser, because i am using get method, is there a way to do that.
Please be nice with your comments. Thanks in advance.!!!
Trying to create a function that would be used to update any row of any table, but I'm getting trouble getting into it.
Data sent in array where the array index is the field name in table and the value is the new value for that index.
For examplpe:
$args["name"] = "NewName";
$args["city"] = "NewCity";
$args["id"] = 4; // row ID to update
What I got:
function create_update_query($table, $keys){
$keys = array_map('escape_mysql_identifier', $keys);
$table = escape_mysql_identifier($table);
$updates = "";
$count = 0;
foreach($keys as $index => $value){
if($index != "id"){
$count++;
if($count == count($keys)-1){
$updates = $updates . "$index = ?";
}else{
$updates = $updates . "$index = ?,";
}
}
}
return "UPDATE $table SET $updates WHERE id = ? LIMIT 1";
}
After that, I have the function to really do the query:
function crud_update($conn, $table, $data){
$sql = create_update_query($table, array_keys($data));
if(prepared_query($conn, $sql, array_values($data))){
$errors [] = "OK";
}else{
$errors [] = "Something weird happened...";
}
}
The function that makes the prepared statement itself:
function prepared_query($mysqli, $sql, $params, $types = ""){
$types = $types ?: str_repeat("s", count($params));
if($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param($types, ...$params);
$stmt->execute();
return $stmt;
} else {
$error = $mysqli->errno . ' ' . $mysqli->error;
echo "<br/>".$error;
}
}
When trying to submit the data with the following criteria:
$args['name'] = "Novo Nome";
$args['field'] = "New Field";
$args['numaro'] = 10101010;
$args['id'] = 4;
//create_update_query("teste_table", $args);
crud_update($link, "teste_table", $args);
Have an error:
1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1 = ?,2 = ?,3 = ? WHERE id = ? LIMIT 1' at line 1
But if I echo the query created by create_update_query it seems ok:
UPDATE `teste_table` SET name = ?,field = ?,numaro = ? WHERE id = ? LIMIT 1
Any help would be appreciated.
Thanks.
The problem is that as you pass the keys to create_update_query() as
create_update_query($table, array_keys($data));
Using array_keys() will just take the key names, so the $keys parameter is just a list of the field names as something like ...
Array(
0=> 'name',
1 =>'field',
2 =>'numaro'
)
You then extract the data using
foreach($keys as $index => $value){
and build your SQL with
$updates = $updates . "$index = ?";
so at this point, the indexes are the numeric value, so change these lines to...
$updates = $updates . "$value = ?";
which is the name of the field.
With the various other changes, I would suggest the code should be...
foreach($keys as $value){
if($value != "id"){
$updates = $updates . "$index = ?,";
}
}
$updates = rtrim($updates, ",");
return "UPDATE $table SET $updates WHERE id = ? LIMIT 1";
So I made a query which returns many restaurants and I put them in a variable $row:
<?php if(count($Result_restaurants)>0)
{
foreach($Result_restaurants as $row)
{ ?>
<div id="ForEveryRestaurant">
<?php
$Rest_Name = $row['name'];
//$Rest_Name = $row;
$stmt = $db->prepare("SELECT Restaurant.idRestaurant FROM Restaurant WHERE Restaurant.name = \"$Rest_Name\"");
$stmt->execute();
$idRestaurant = $stmt->fetch();
$avg = 0;
$rateSum = 0;
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
$stmtcard = $db->prepare($strcard);
$stmtcard->execute();
$result = $stmtcard->fetchAll();
if (count($result) === 0)
{
return 0;
}
foreach( $result as $coments)
{
$rateSum += $coments['rating'];
}
$avg = $rateSum / count($result);
$avg = round($avg, 1);
When I try to run my code, it prints Array to string conversion.
The problem appears in this line:
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
I searched about the error and I understand but I tried many resolutions and didn't solved the problem.
can someone help please?
You should do like the following
$stmt->execute();
$stmt->bind_result($idRestaurant);
$stmt->fetch();
Try For PDO:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$idRestaurant = $result['idRestaurant'];
The problem is in this statement
$idRestaurant = $stmt->fetch();
Have you tried $idRestaurant = $stmt->fetch()[0];?
You can actually check what's coming into $idResturant by checking it via var_dump
var_dump($idResturant)
Check this:
$idRestaurant = $stmt->fetch();
// Its an array and you cannot use an array directly with WHERE clause in a query. Convert it to normal variable and use it.
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
// here you are using the array in WHERE clause
To do this:
$rating = isset($stmt->fetch()[0]) ? $stmt->fetch()[0]: null;
I have a table with columns that allow null values and has a default null value. On update, if the field is empty (not data inserted) my script inserts 0 instead of null. I have gone through similar questions as mine and i have tried the advice given but am still not able to fix my issue. Here's my code
<?php
if (isset($_POST['submit'])) {
# process the form
$student_id = $_POST["student_id"];
$subject_id = $_POST['subject_id'];
if (is_null($_POST["test1"])){$test1 = null;} else {$test1 = $_POST["test1"];}
if (is_null($_POST["test2"])){$test2 = null;} else {$test2 = $_POST["test2"];}
if (is_null($_POST["test3"])){$test3 = null;} else {$test3 = $_POST["test3"];}
for($i=0; $i < count($student_id); $i++) {
$studentid = mysqli_real_escape_string($connection, $student_id[$i]);
$subjectid = mysqli_real_escape_string($connection, $subject_id);
$test_1 = mysqli_real_escape_string($connection, $test1[$i]);
$test_2 = mysqli_real_escape_string($connection, $test2[$i]);
$test_3 = mysqli_real_escape_string($connection, $test3[$i]);
$query = "UPDATE fullresult SET test1='{$test_1}', test2='{$test_2}', test3='{$test_3}' WHERE student_id={$studentid} AND subject_id={$subjectid}";
$result = mysqli_query($connection, $query);
}
}
?>
When i echo the query, this is what i see and am wondering why i still get 0 inserted
UPDATE fullresult SET test1=' 10', test2=' ', test3=' ' WHERE student_id=51 AND subject_id=2
is_null does not return true for an empty string. Try changing your if statements to something like this:
$test1 = trim($_POST["test1"])
if (!strlen($test1)) $test3 = null;
You could use
ctype_digit
to check if there are numeric characters in it.
The function
mysqli::real_escape_string -- mysqli_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
(Source: http://php.net/manual/en/mysqli.real-escape-string.php)
Since you want to have null inside the database you should rewrite the code
if (is_null($_POST["test1"])){$test1 = null;} else {$test1 = mysqli_real_escape_string($connection, $_POST["test1"]);}
to have the values escaped only if needed (which is in case you have a value in $_POST)
What about
if (isset($_POST['submit'])) {
# process the form
$student_id = $_POST["student_id"];
$subject_id = $_POST['subject_id'];
# only retrieve FILLED IN answers
$tests = array();
if(isset($_POST["test1"]) && strlen($_POST["test1"])) $tests['test1'] = $_POST["test1"];
if(isset($_POST["test2"]) && strlen($_POST["test2"])) $tests['test2'] = $_POST["test2"];
if(isset($_POST["test3"]) && strlen($_POST["test3"])) $tests['test3'] = $_POST["test3"];
if(!empty($tests)){ # if there were no answers, there's no point in updating the database
for($i=0; $i < count($student_id); $i++) {
$studentid = mysqli_real_escape_string($connection, $student_id[$i]);
$subjectid = mysqli_real_escape_string($connection, $subject_id);
# now let's build the "SET" part of the query
$set = array();
foreach($tests as $key => $value) $set[]=mysqli_real_escape_string($key)."='".mysqli_real_escape_string($value)."'";
$set = implode(', ',$set);
# ...and finally update
$query = "UPDATE fullresult SET {$set} WHERE student_id={$studentid} AND subject_id={$subjectid}";
$result = mysqli_query($connection, $query);
}
}
}
The point of this approach is that if you don't include a key=>value pair in your UPDATE query, it will be filled in with its default value.
You must set 'null' word, not null value.
if (is_null($_POST["test1"])){$test1 = 'null';} else {$test1 = $_POST["test1"];}
if (is_null($_POST["test2"])){$test2 = 'null';} else {$test2 = $_POST["test2"];}
if (is_null($_POST["test3"])){$test3 = 'null';} else {$test3 = $_POST["test3"];}
I have problem undefined variable. The thing is, I found a tutorial to make a type micro blog Twitter, had some problems, I decided, but this is taking me patience.
Error Message:
Notice: Undefined variable: extra in caminho\do\arquivo\functions.php on line 58
function:
function show_users($user_id=0){
if ($user_id > 0){
$follow = array();
$fsql = "SELECT user_id FROM following WHERE follower_id='$user_id'";
$fresult = mysql_query($fsql);
while($f = mysql_fetch_object($fresult)){
//array_push($follow, $f->user_id);
$follow[] = $f->user_id;
}
if (count($follow)){
$id_string = implode(',', $follow);
$extra = " AND id IN ($id_string)";
}else{
return array();
}
}
$users = array();
$sql = "SELECT id, username FROM users WHERE status='active' $extra ORDER BY username";
$result = mysql_query($sql);
while ($data = mysql_fetch_object($result)){
$users[$data->id] = $data->username;
}
return $users;
}
The line in question is:
$sql = "SELECT id, username FROM users WHERE status='active' $extra ORDER BY username";
Any suggestions?
There are two ways :
1. function show_users($user_id=0){
$extra='';
2. function show_users($user_id=0,$extra=''){
Actually you are declaring $extra only when you have $user_id > 0 BUT you must be having $user_id equals to or less than 0 for the current situation and thus your query couldn't find $extra.
I hope you get an idea.
function show_users($user_id=0){
$extra = ''; //if no extra, you'll get just an empty string
//etc...
}
function show_users(...) {
$extra = ''; // <--just add this line
blah blah blah blah blah
}
In your code, $extra gets defined ONLY if both if() tests succeed. Obviously they're not, so you end up with an undefined $extra in your sql string.
function show_users($user_id=0,extra='') // use this
{
if ($user_id > 0){
$follow = array();
$fsql = "SELECT user_id FROM following WHERE follower_id='$user_id'";
$fresult = mysql_query($fsql);
while($f = mysql_fetch_object($fresult)){
//array_push($follow, $f->user_id);
$follow[] = $f->user_id;
}
if (count($follow)){
$id_string = implode(',', $follow);
$extra = " AND id IN ($id_string)";
}else{
return array();
}
}