php multiple record insert to sql not working - php

Hi all I have a form where I'm entering students marks for exams, what I am trying to do is enter multiple marks in at once...but it just is not working, could someone help please? It is adding only ONE result, doesn't enter all that I write in.
FORM Code:

The script does not know what is $i in this case.
Use for loop:
$mark=$_POST['mark'];
$time=$_POST['time'];
$meID=$_POST['meID'];
$sID=$_POST['sID'];
for($i = 0; $i < count($_POST['mark']); $i++) {
$_mark = mysql_escape_string($mark[$i]);
$_time = mysql_escape_string($time[$i]);
$_meID = mysql_escape_string($meID[$i]);
$_sID = mysql_escape_string($sID[$i]);
$sql = "INSERT INTO Marks (mark, time, meID, sID) VALUES ($_mark, $_time, $_meID, $_sID)";
$result = mysql_query($sql);
}
Additionally you will add each mark twice, because of two mysql_query() invocations. I've already deleted one from $sql variable in my answer. Also you have wrong variable names in the insert query.

I think the problem is with the variable names:
Following line:
$sql = "SELECT * FROM ModuleExamStudent WHERE mesID = '$mesID'";
But there is no $mesID. It should be $mes:
$sql = "SELECT * FROM ModuleExamStudent WHERE mesID = '$mes'";
Again:
$sql = mysql_query("INSERT INTO Marks (mark, time, meID, sID) VALUES ('$mark', '$time', '$meID', '$sID')");
Should be:
$sql = mysql_query("INSERT INTO Marks (mark, time, meID, sID) VALUES ('$_mark', '$_time', '$_meID', '$_sID')");

there is no mysql_escape_string . try replace this;
$_mark = mysql_escape_string($mark[$i]);
to
$_mark = mysql_real_escape_string($mark[$i]);
and put $_mark in the query instead of $mark
and replace all others also.

Yeah, a lot of mistakes in you're code.
Fuse michal.hubczyk and Ambrish answer to obtain wath you want.
If i can suggest another way to do it, i'll prefer to make only one query instead an elevated number of query succession inside a loop.
Try this method
Inserting multiple rows in a single SQL query?
and build your query in a way like this:
$sql = "INSERT INTO XX VALUES";
for($i=0;$i < count($_POST['mark']); $i++){
$_mark = mysql_escape_string($mark[$i]);
$_time = mysql_escape_string($time[$i]);
$_meID = mysql_escape_string($meID[$i]);
$_sID = mysql_escape_string($sID[$i]);
$sql .= "(".$_mark.",".$_time",".$_meID.",".$sID.")";
if($i<(count($_POST['mark']-1))){
$sql .= ",";
}
$result = mysql_query($sql);
Another suggestion is to use mysqli libray instead mysql ( http://php.net/mysqli)

Related

Conditional PDO Delete statement probably not working

The portion that is trying to delete duplicate entries in the database seems incorrect. So I suppose I am asking what would be the correct way to do that in this example. I am not totally new to PHP , but this is beyond me. If you could please tell me what is wrong and how to fix that would be greatly appreciated.
Now on to what I am trying to accomplish. I have a multidimensional array filled with values that is generated by a function. What I am trying to do is if there is a value in the array that already exists in the database delete it. Code:
enter code here
if(is_array($items)){
$values = array();
foreach($items as $row => $value){
$rsn = mysqli_real_escape_string($connect, $value[0]);
$rank = mysqli_real_escape_string($connect, $value[1]);
$values[] = "('', '$rsn', '$rank', '')";
$sql = "SELECT id FROM users WHERE rsn = :rsn";
$query = $conn->prepare($sql);
$query->execute(array(":rsn" => $value[0]));
$results = $query->rowCount();
while($deleted = $query->fetch(PDO::FETCH_ASSOC)){
$sql = "DELETE FROM users WHERE id = :id";
$query = $conn->prepare($sql);
foreach($deleted as $delete){
$query->execute(array(':id' => $delete));
}
}
}
//user_exists_delete($conn, $rsn);
$sql = "INSERT INTO users(id, rsn, rank, points) VALUES ";
$sql .= implode(', ', $values);
if(!empty($rank)&& !empty($rsn)){
if(mysqli_query($connect, $sql)){
echo "success";
}else{
die(mysqli_error($connect));
}
}
}
EDIT: I have got it partially working now, just need it to delete all dupes instead of only one. I edited code to reflect changes.
There are a couple problems, if you didn't strip much of your original code and if you don't need to do more than just what you shown why not just send a delete instruction to your database instead of checking validity first?
You have
//Retrieve ID according to rsn.
$sql = "SELECT id FROM users WHERE rsn = :rsn ";
//Then retrieve rsn using rsn??? Useless
$sql = "SELECT rsn FROM users WHERE rsn = :rsn ";
//Then delete using ID, retrieved by rsn.
$sql = "DELETE FROM users WHERE id = :id";
All those could simply be done with a delete using rsn...
$sql = "DELETE FROM users WHERE rsn = :rsn";
The row won't be deleted if there are no rows to delete, you don't need to check in advance. If you need to do stuff after, then you might need to fetch information before, but if not, you can use that while still checking the affected rows to see if something got deleted.
Now, we could even simplify the script by using only one query instead of one per user... We could get all rsn in an array and then pass it to the DELETE.
$sql = "DELETE FROM users WHERE rsn in :rsn";
//Sorry not exactly sure how to do that in PDO, been a while.
I fixed it I just omitted the WHERE clause in the delete statement so all records are being deleted before that insert gets ran again.

How to compare input from a user php post to a MySQL

I am teaching myself php and MySQL, and right now I have a problem with MySQL.
I want to compare the phone number that the user put in with the phone number in MYSQL, and if it is in MYSQL to not register it again.
My code:
<?php
require_once 'connection/connection.php';
// Variables from HTML to php
$worker_Name = $_POST['workerNameFromHtml']; // worker Name
$worker_City = $_POST['workerCityFromHtml']; // workerCity
$worker_career = $_POST['workerCareerFromHtml']; // worker career
$worker_PhoneNumber = $_POST['workerPhonNumberFromHtml']; // worker Phone Number
$worker_SecondPhoneNumber = $_POST['workerSecondPhoneNumberFromHtml']; // worker Second Phone Number
$submt=$_POST['submitFromHtml'];
if($submt){
$qry = ( "SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'") or die(mysql_error());
$result = $connect->query($qry);
$num = $result->num_rows;
if ($num == 1) {
$here = "INSERT INTO workersTable VALUES('','$worker_Name','$worker_City','$worker_career','$worker_PhoneNumber','$worker_SecondPhoneNumber')";
$query = $connect->query($here);
print "Successfully added!";
}
else {print "This number has already been entered Thank you for your cooperation!";}}
$connect->close();
So far I have not found a solution to this problem.
your biggest problem here is that you are trying to include variables inside of a string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '$worker_PhoneNumber'"
If you want to do it this way, you need to concatenate your variables with your string.
"SELECT workrPhoneNumber FROM workersTable WHERE workrPhoneNumber = '".$worker_PhoneNumber."'"
Keep in mind if you do this you will want to sanitize your variables first to prevent SQL injections. Also, when you INSERT variables, you will actually want to use a prepared statement like this:
"INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
where the 1st set of values are the names of your columns in the database and the second set are your PHP variables you are putting into it.

Better way of inserting multiple strings in a mysql database

So, I've got a few txt files, each container around 400,000 lines.
Each line is a word, I need to add to my database, if it isn't in there already.
Currently my code for checking/adding every word is
$sql = mysql_sql("SELECT `id` FROM `word_list` WHERE `word`='{$word}' LIMIT 1");
$num = mysql_num($sql);
if($num == '0'){
$length = strlen($word);
$timestamp = time();
#mysql_sql("INSERT INTO `word_list` (`word`, `length`, `timestamp`) VALUES ('{$word}', '{$length}', '{$timestamp}')");
}
and the functions being called are:
function mysql_sql($sql){
global $db;
$result = $db->query($sql);
return $result;
}
function mysql_num($result){
return $result->num_rows;
}
I'm looking for a better way to insert each word into the database.
Any ideas would be greatly appreciated.
I can think of some ways to do this.
First, if you have access to the MySQL server's file system you can use LOAD DATA INFILE to create a new table, then do an insert from that new table into your word_list table. This will most likely be your fastest option.
Second (if you don't have access to the MySQL server's file system), put a primary key or unique index on word_list.word. Then get rid of your SELECT query and use INSERT IGNORE INTO word_list .... That will allow MySQL automatically to skip the duplicate items without any need for you to do it with a query/insert operation.
Third, if your table uses an access method that handles transactions (InnoDB, not MyISAM), issue a BEGIN; statement before you start your insert loop. Then every couple of hundred rows issue COMMIT;BEGIN; . Then at the end issue COMMIT;. This will wrap your operations in multirow transactions so will speed things up a lot.
Try out this code. It will first create query with all your values and you will run query only ONCE ... Not again and again for ever row
$values = array();
$sql = mysql_sql("SELECT `id` FROM `word_list` WHERE `word`='{$word}' LIMIT 1");
$num = mysql_num($sql);
$insert_query = "INSERT INTO `word_list` (`word`, `length`, `timestamp`) VALUES ";
if ($num == '0') {
$length = strlen($word);
$timestamp = time();
$values[] = "('$word', '$length', '$timestamp')";
}
$insert_query .= implode(', ', $values);
#mysql_sql($insert_query);

php query-loop does not work

I have this code:
public function updateOrder($num, $ufood, $uquan) {
$response = array();
mysql_query("SET NAMES 'utf8'");
foreach ($ufood as $index => $f) {
$result = mysql_query("SELECT food, quantity, uquantity FROM table1 WHERE food ='".$f."'") or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
$response['number rows'] = $no_of_rows;
if ($no_of_rows>0) {
while ($row = mysqli_fetch_array($result)); {
if (!$row['uquantity']) {
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
mysql_query($w);
$e = (int)$row['quantity'];
$q = (int)$uquan[$index];
$sum = $e+$q;
$s = (string)$sum;
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
mysql_query($d);
} else if($row['uquantity']) {
$c = (int)$row['uquantity'];
$q = (int)$uquan[$index];
$sumq = $c+$q;
$sq = (string)$sumq;
$d = "UPDATE table1 SET uquantity = '$sq' WHERE food = ".$row['$food']." ";
}
}
} else {
$string ="INSERT INTO table1(food,uquantity) VALUES ('".$f."','".$uquan[$index]."')";
$z = mysql_query($string);
}
}
}
Well i can not make this work, and i am trying all kinds of things put still it doesn't work.
So i have some questions:
Is this structure of foreach and while valid?
Though the $result query returns some rows from the database, when i try to use $row['quantity'], as a value, i get null.
In this code i receive some data from an android app, and i try to "see", if there are already entries for the type food of my db_table(table1). If there are entries i want the db to sum the quantity entry of the android sent, data with the one that are inside my db, and update the field. This is the basically it. But as i said when i try to use the data that comes from the database, i get null values.
Please if someone could give me some hint, cause I'm really stuck..
There are many problems with your code. I'm marking this answer as Community Wiki, and I invite others to edit and add things as they find them.
You may also consider posting to https://codereview.stackexchange.com/ instead, when you have so many mistakes, until you have a more specific question.
Bad variable interpolation
This line won't do what you want it to:
$w = "INSERT INTO table1(uquantity) VALUES ('$uquan[$index]')";
This is not quite valid PHP syntax. You can either concatenate expressions:
$w = "INSERT INTO table1(uquantity) VALUES ('".$uquan[$index]."')";
Or you can embed expressions in curly braces:
$w = "INSERT INTO table1(uquantity) VALUES ('{$uquan[$index]}')";
Or you can use a query parameter placeholder:
$w = "INSERT INTO table1(uquantity) VALUES (?)";
$stmt = mysqli_prepare($w) or die(mysqli_error());
$uqi = $uquan[$index];
mysqli_stmt_bind_param($stmt, "i", $uqi);
mysqli_stmt_execute($stmt);
Mixing MySQL APIs
You can't mix mysql_query() with mysqli_fetch_array(). PHP has more than one API for MySQL, and you can't mix them. You should standardize on using the mysqli API, because the older mysql API is now deprecated.
Semicolon defeats while loop
The semicolon after the while statement makes the loop a no-op, and when it terminates, the $row contains nothing.
while ($row = mysqli_fetch_array($result)); {
Should be:
while ($row = mysqli_fetch_array($result)) {
Using variables inappropriately
Referencing a $row key with a single-quoted variable is probably not what you mean, in multiple ways:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = ".$row['$food']." ";
The column name in the select-list of your earlier SELECT query is 'food', not '$food'.
Also, even if you meant to use a variable name $food as the key, putting it in single quotes would not use the value of the variable, it would be the literal string '$food'.
Failure to quote string literal?
Furthermore, you use a quoted literal for comparing to the food column in your SELECT query, which makes me think it might be a string.
So the UPDATE should be something like:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = '".$row['food']."' ";
Or:
$d = "UPDATE table1 SET quantity = '$s' WHERE food = " . intval($row['food']);
Or preferably use parameters and a prepared query, then you don't need to worry about quotes or types:
$d = "UPDATE table1 SET quantity = ? WHERE food = ?";
. . .
Failure to check for errors
Every query might fail, either because you have a syntax error (e.g. a string without quoting), or because the table doesn't have a column by the name you reference, or privileges issues, etc.
Always check the return status of the query function when you run a SQL query. The function returns false if there's an error, and if that happens you must check the error message.
mysqli_query($mysqli, $d) or trigger_error(mysqli_error($mysqli), E_USER_ERROR);
Failure to execute the UPDATE
Your second update assigns a SQL query string to the variable $d, but then does not execute that update query at all!

mysql_query(INSERT ...) function not working in my code

I've create database, which basically accept name and Id and answer string of
length 47,and my php code will grade the incoming results against the answer key I provided and number containing the count of correct answers will stored in database. this is information of my database.
database name is marking
and table called 'answer', which has 5 fields as follow
1) answer_id :int , not null, auto increament.
2) name: text
3)id : text
4)answers : text
5)correct : int
my question and problem is the function is working
// setup query
$q = mysql_query("INSERT INTO `answer` VALUES
(NULL,'$name', '$id','$answers','$correct')");
// run query
$result = mysql_query($q);
or in another way , nothing storing in my database ???
Thanks in advance.
this is the whole program.
<?php
error_reporting(E_ALL ^ E_STRICT);
// to turn error reporting off
error_reporting(0);
$name =$_POST['name'];
$id = $_POST['id'];
$answers = $_POST['answers'];
// check the length of string
if(strlen($answers) !=10)
{
print'your answer string must be 10';
return;
}
mysql_connect("localhost","root","");
mysql_select_db("marking");
$name = addslashes($name);
$id = addslashes($id);
$answers = addslashes($answers);
$answer_key = "abcfdbbjca";
$correct = 0;
for($i=0;$i<strlen($answer_key);$i++)
{
if($answer_key[$i] == $answers[$i])
$correct++;
}
// Setup query
$q = mysql_query("INSERT INTO `answer` VALUES ('$name', '$id','$answers','$correct')");
$result = mysql_query($q);
print 'Thnak you. You got' + $correct + 'of 10 answers correct';
?>
Try this:
// setup query
$q = "INSERT INTO `answer` (`name`, `id`, `answers`, `correct`) VALUES
('$name', '$id','$answers','$correct')";
//Run Query
$result = mysql_query($q) or die(mysql_error());
Also, you should avoid using mysql_ functions as they are in the process of being deprecated. Instead, I recommend you familiarize yourself with PDO.
Also, note, the or die(mysql_error()) portion should not be used in production code, only for debugging purposes.
Two things.
You are actually executing the query twice. mysql_query executes the query and returns the result resource. http://php.net/manual/en/function.mysql-query.php
And also, you are quoting the int column correct in your query, as far as I know, you can't do that (I could be wrong there).
$result = mysql_query("INSERT INTO `answer` VALUES (NULL,'$name', '$id','$answers',$correct)");
EDIT: Turns out I'm actually wrong, you may disregard my answer.

Categories