I have an insert process. My development is under Drupal6. So i used the following method to insert into database table.
$sid = $user->sid;
$data = array(
'nid' => $parent_nid,
'vid' => $parent_vid,
'uid' => $user_id,
'time_start' => time(),
'session_id' => $sid
);
drupal_write_record('quiz_node_results', $data);
Here the problem is, it is not inserting the value $sid. It inserts the default value 0 always in that field. But other values are inserted correctly. But it has value. I checked with by putting print_r($data).
In database table, session_id field's datatype is varchar.
For quick fix, i wrote actual insert query and inserted into it. That query is below.
$sql = "INSERT INTO {quiz_node_results}(nid, vid, uid, time_start, session_id) VALUES(".$parent_nid.",".$parent_vid.",".$user_id.",".time().", '".$sid."')";
db_query($sql);
It is working fine and inserts the value correctly. But i don't want to insert in this way because it is vulnerable.
I want to know why the above one is not working. Can anyone suggest where i went wrong?
I'm pretty sure changing line 1 from this:
$sid = $user->sid;
to this:
$sid = isset($user->sid) ? $user->sid : session_id();
should do the trick...
Related
I have file PHP by this file I update the data in MySQL table. I send data to this PHP file from flutter app but there are one problem I have 3 field in this file so user can update data in those 3 Column in MySQL table to here every thing is ok but my problem if user send just one Column data from flutter app to PHP file the data will update in this Column but the others Column will will become null.
So how I can make this file make skip to any empty column the user not send data to it?
I need the old data not be changed in the database if the file does not get new data for that column.
Thank you.
PHP file:
<?php
require_once 'con.php';
$id = $_POST['id '];
$IDbook= $_POST['IDbook'];
$IDbookset= $_POST['IDbookset'];
$sql="UPDATE topics SET IDbook= ? ,IDbookset=? WHERE id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param("sss",$IDbook,$IDbookset,$id);
$stmt->execute();
$result = $stmt->get_result();
$exeQuery = mysqli_query($con, $sql) ;
if($exeQuery){
echo (json_encode(array('code' =>1, 'message' => 'Modifier avec succee')));
}else {echo(json_encode(array('code' =>2, 'message' => 'Modification Non Terminer')));
}
?>
One way to do it is to
Fetch the data for the current $id say into $OldIdbook and $OldIdbookset
get updated values like this $IDbook= $_POST['IDbook'] ?? $oldIDbook; This uses the old value if the $_POST is null.
then execute the query to update.
The second way is to construct the query by adding only the field=value pairs that have changed to the query. Its a little bit more work to handle the comma.
I have a huge multistep form with data for multiple tables in mysql db. For every field my html is like-
input type="text" name="names" value="" // value set using php echo
On submit at php I am doing this for all the fields of my form-
$name=$_POST['names'] ?? ' '
to avoid unidentified index and unidentified variable
Then i update my first table and write log that its updated.
$query=mysqli_query($con,"UPDATE teacherpersonal set name='$name' ... where id=$id");
write_mysql_log("teacherpersonal updated", "facultydetails", $id).
I have defined write_mysql_log.
And similarly i update all the remaining tables with either the updated values or blank ("") values.
Since you can see that update query always executes even if the fields are not changed. Hence it is always logged that the tables are updated. But that's not what I want. I want to update only those fields in the table which are changed and remaining stay intact and log only those tables which are thus updated. Many tables won't be updated this way as the user might change only few details.
Using jquery and php.
My write_mysql_log is
function write_mysql_log($message, $db, $faculty_id)
{
$con=mysqli_connect("localhost","root","");
mysqli_select_db($con,"facultydetails");
// Construct query
$sql = "INSERT INTO my_log (message, faculty_id) VALUES('$message', '$faculty_id')";
$query=mysqli_query($con, $sql);
// Execute query and save data
if($query) {
echo 'written to the database';
}
else {
echo 'Unable to write to the database';
}
}
This you can achieve in 2 different ways.
1) With the help of jQuery check the values which are updated, post only those values to the php script
2)At the time of updating the check the current values with the updated one based on that criteria update the db tables.
solution 1 is less time taking process compare to the other.
You need to update only the user edited value, by doing this you can achieve it;
$oldvalue = array("username" => "green", "email" => "green#mail.com","dob" => "111");
$newvalue = array( "email" => "green#mail.com","dob" => "111","username" => "blue");
$updates = array_diff($newvalue, $oldvalue);
$implodeArray = implode(', ', $updates);
$sql = ("UPDATE user WHERE userID=$userID SET $implodeArray");
mysql_query($sql,$this->_db) or die(mysql_error());
mysql_close();
Output:
$updates = array_diff($newvalue, $oldvalue);
will have:
Array ( [username] => blue )
which is changed one
Ok after considering many options like-
create json object for old and new data and then compare and check which values changed and update that table and log it.
Or create a php array with old and new data and check diff then do the same (as suggested by Ram Karuppaiah)
Or a bad idea to have a flag on every input and then mark which ones have changed using onkeyup jquery event then try to update only those fields tables.
So finally what i did is that i let the form get submitted with all the data. As earlier i am taking the data in php as $name=$_POST['names'] ?? ' ' (blank if nothing is submitted or if something submitted then its value).
Before update statement in php, i am querying the table and comparing the database values with the values i got, if all same i dont do anything. If not then i update the table with the new values and log the change.
I have a MySQL database with a backend: PHP.
In one table I have to insert 60,000 rows.
We made a query into my PHP that returns 1,000 rows. For each rows we have to insert 60 rows. We thought make a loop but we don't know if is the best practices that way.
The part of the code that insert the data is:
$turnos = $db->query("SELECT * FROM turno t
WHERE t.canchaId = :cancha
AND t.fecha BETWEEN :fechaInicio AND :fechaFin
AND t.nombre LIKE :cadena
ORDER BY t.fecha,t.hora ASC",
array("cancha" => $cancha["idCancha"], "fechaInicio" => $fechaInicio, "fechaFin" => $fechaFin, "cadena" => "%turno fijo%"));
foreach($turnos as $turno) {
//turnos have 1000 rows
$fecha = date_create($turno["fecha"]);
date_add($fecha, date_interval_create_from_date_string('7 days'));
$anioAuxiliar = 2017;
while(2017 == $anioAuxiliar){
//60 times
$data1 = turno[data1];
$data2 = turno[data2];
...
$fechaAGuardar = (String) $fecha->format('Y-m-d');
$result = $db->query("INSERT INTO turno(fechaAGuardar, data2, data3, data4, data5, data6, data7, data8) VALUES(:fechaAGuardar, :data2, :data3, :data4, :data5, :data6, :data7, :data8)",
array("fechaAGuardar" => $fechaAGuardar, "data2" => $data2, "data3" => $data3, "data4" => $data4, "data5" => $data5, "data6" => $data6, "data7" => $data7, "data8" => $data8));
date_add($fecha, date_interval_create_from_date_string('7 days'));
$anioAuxiliar = (int) $fecha->format("Y");
}
$cantidad_turnos = $cantidad_turnos + 1;
}
This php is into a hosting with phpmyadmin.
So my questions are:
This is the best way to insert 60,000 rows?
Shall we considerer take into account another constraint? (eg: phpmyadmin don't allow you insert that amount of rows)
Thanks for helping me, Any suggestions are welcome
//EDIT//
The inserts data change, we have to insert datetime, and for each loop we have to add 7 day the last date inserted. So we can't use insert with select
As a bunch of fellows described in the comments, INSERT/SELECT is the way to go if this data is in the same server/database. There's no need to use PHP at all. Your year comment can be handled with DATE_ADD.
Anyway, if there is any other requirement and you can't use PHP, consider using Bulk Data Loading.
Analysing your code, the MOST IMPORTANT TIP would be: don't use multiple INSERT INTO TABLE expressions. Each INSERT INTO will cause a round trip do the database and things will get really slow. Instead of it, concat multiple values with one INSERT INTO (example from the link):
INSERT INTO yourtable VALUES (1,2), (5,5), ...;
Good luck!
Got the lower portion here sorted, but now there's an issue when it inserts the record. I have the NULL value for file formatted as %s for string, but it's not inserting NULL it's inserting [BLOB - 0B]. The column format in the mySQL table is longblob. Any ideas?
this is my first time using $wpdb->insert and it looks like I've missed something.
Here's the loop I'm trying to use. There are currently 2 timestamps in the array.
for ( $i = 0; $i < count($timestamps); $i++ ) {
$working_time = $timestamps[$i];
$working_form = $formnames[$i];
$status_data = array(
'submit_time' => $working_time,
'form_name' => $working_form,
'field_name' => 'lead_status',
'field_value' => 'new',
'field_order' => 10001,
'file' => NULL
);
$status_data_types = array(
'%f',
'%s',
'%s',
'%s',
'%d',
'%s'
);
$result = $wpdb->get_results("SELECT field_value FROM ".$leadtable." WHERE submit_time = ".$working_time);
if(!$result) {
$insert = $wpdb->insert($leadtable, $status_data, $status_data_types);
if( !$insert ) {
echo 'didn\'t work';
}
}
}
I know that $working_time and $working_form are both set properly. $working_time is a long float like 1387175380.9600 and $working_form is a string.
Nothing is being returned, even by the if( !$insert ) check so I'm guessing it's erring somewhere before that point. I know that if( !$result ) will return true because that data does not exist yet.
Found the issue. The get_results query was failing due to a missed period. My HS English teacher was right... a missed period can be a HUGE problem!
If you want to get the last error and last query you can use this properties of $wpdb object:
$wpdb->last_error
will show you the last error, if you got one.
$wpdb->last_query
will assist you with showing the last query (where the error occurred)
I hope this will help you out.
Maybe your config hides error showing. Have you tried $wpdb->print_error();?
https://core.trac.wordpress.org/ticket/32315
One of the columns inputs may be larger than the column is.
Wordpress detects this and will not even send the query to the DB.
The Diff there shows a patch for wp-db you can put in to get more information in the last_error message so it will not be empty.
Hopefully, you have defined the global variable $wpdb.
If your $wpdb is not working, and also not showing any error then you must try these three steps.
Print your error using with errors functions.
echo $wpdb->last_error;
or
echo $wpdb->show_errors;
If no error is visible then you must print your last query using with last query function.
echo $wpdb->last_query;
Copy and paste your last query in your Phpmyadmin > Your Database -> Table -> SQL tab, click on the Go button, and you will definitely get proper solutions(errors) in it.
I'm running a codeigniter application, and i can't get this simple insert to work well.
if(!$this->db->insert('myTable',$entry)){
$p3 = 0;
}else{
echo $this->db->last_query();
var_dump($this->db->_error_message());
}
the debug in the "else" clause always show me an empty string for error message, and if i test the last_query in phpmyadmin, the insert work well.
But the insert isn't happening when i normally run the app, even if the "else" is launched, implying the request succeed.
any clue ?
UPDATE : exemple of $entry array :
$entry = array(
'id' => '',
'id_devis' => $current[0]->id,
'metier' => $_POST[$i+1 . '_create_metier'],
'days' => $_POST[$i+1 . '_create_daycount'],
'price' => $_POST[$i+1 . '_create_price'],
'cr_date' => date('Y-m-d H:i:s'),
'user' => ''
);
$current is an extract of another table (using $this->db->get), and all the datas are fine, since i can insert them through the echo of last_query()
Put
error_reporting(E_ALL);
ini_set('display_errors', '1');
before the line with the insert. You should see an error message.
My guess is that you try to insert an illegal value for id. Possible reasons:
- It should not be empty.
- It can not be a string (ie. if the type is an integer)
Most of the time an id in the database is of type int and is an auto-increment field. If so, you should not try to insert an id. It will be created for you.
Just found out the issue, there wasn't. a script was deleting the line i just inserted further in the code, the insert was successful. Thanks for your answers all