I would like to ask if how can the SQL rearrange the database simultaneously after there is an new input.
Sample data:
I want to follow the Hybrid FCFS + Priority where 1:1 ratio, 1 regular and 1 priority simultaneously.
The identifier of Priority here is when the Priority = 1 of that input.
Here the sample PHP script code but I am stucked here, I don't know if I will modify the code in PHP or it is directly statemented in SQL database
function save_queueSAMPLE(){
extract($_POST);
if($priority == 1){
}
else{
$sql = "INSERT INTO `queue_listSAMPLE` (`customer_name`,`priority`) VALUES('{$customer_name}','{$priority}')";
$save = $this->query($sql);
if($save) {
$resp['status'] = 'success';
$resp['id'] = $this->query("SELECT last_insert_rowid()")->fetchArray()[0];
} else {
$resp['status'] = 'failed';
$resp['msg'] = "An error occured. Error: ".$this->lastErrorMsg();
}
return json_encode($resp);
}
}
Related
After read many post about "delete massive amount of rows", I tried several answer for my problem but not work like hope.
Explanation : I've been commendited to transcript a desktop application to a web app. The application have to main goal a update of several sql tables.
When I was working on it, I've been informed to change the truncate method to a delete method. So now we don't do a Truncate and Insert, but a Replace/Insert and Delete all rows not replace/insert into the table.
Here some code :
$codeliste = "";
$req2 = "SELECT projection.article.ean, projection.article.artic
FROM projection.article
WHERE projection.article.annule is null and projection.article.ean is not null";
$req_res2 = mssql_query($req2);
if (mssql_num_rows($req_res2) > 0) {
$nbc = 0;
while ($result = mssql_fetch_row($req_res2)) {
if(trim($result[0]) <> "") {
if($codeliste == "") $codeliste = "'".$result[0]."'";
else $codeliste .= ",'". $result[0]."'";
$req = "REPLACE INTO fean ( bar_code , article ) VALUES ('". trim($result[0]) ."','". trim($result[1]) ."')";
if($connexion->exec($req)) {
$nbc++;
}else{
echo "<br/>Fail Replace fean";
}
}
}
echo "<br/>Exported Ean : ".$nbc."<br/>";
}else{
echo "Fail request at projection.article of ean";
}
if($codeliste <> "") {
$req = "DELETE FROM fean WHERE bar_code NOT IN (".$codeliste .")";
if($connexion->exec($req)) {
echo "Success delete Ean not export";
}else{
echo "Fail at DELETE fean";
}
}else{
echo "codeliste is empty";
}
More Information : I'm not allowed to truncate tables, I can't change the configuration of php.ini and conf.ini, I'm working on a delete up to 50.000~100.000 rows.
With the code above I obtain "SQLSTATE[HY000]: General error: 2006 MySQL server has gone away"
After that I tried tempory table, I obtain for result a loading page who never end (to be sure I waited 1h and no result from the page).
Then I tried to delete 5.000 rows by 5.000 rows with a loop, no more success.
Thanks in advance.
EDIT : I do some research and try to change the way I was deleting for a other way to the NOT IN in the code above, like CBroe suggest.
But I've got one more time "Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away'" when I load my page.
Have you another idea of way to make this page Delete without gone away ?
EDIT2 : I've had some change in my code in the objectif to send less request to the database mysql.
But I've been inform that my request have cause some lag issue because my delete request stay on sleep state in mysql. To be honest i don't know why, if someone could explain me why and maybe how I can avoid this problem in futur I would be grateful.
Here my code now : my goal was to reduce the number of request sql I send to the database.
$codeliste = array();$codesuppr = array();
$req2 = "SELECT projection.article.ean, projection.article.artic
FROM projection.article
WHERE projection.article.annule is null and projection.article.ean is not null";
$req_res2 = mssql_query($req2);
if (mssql_num_rows($req_res2) > 0) {
$nbc = 0;
while ($result = mssql_fetch_row($req_res2)) {
if(trim($result[0]) <> "") {
array_push($codeliste, trim($result[0]));
$req = "REPLACE INTO fean ( bar_code , article ) VALUES ('". trim($result[0]) ."','". trim($result[1]) ."')";
if($connexion->exec($req)) {
$nbc++;
}else{
echo "<br/>Fail Replace fean";
}
}
}
echo "<br/>Exported Ean : ".$nbc."<br/>";
}else{
echo "Fail request at projection.article of ean"
}
if (!empty($codeliste)) {
$req = "SELECT bar_code FROM fean";
$resultats = $connexion->query($req);
foreach($resultats AS $resultat) {
if (!in_array(trim($resultat), $codeliste)) {
array_push($codesuppr, trim($resultat));
}
}
if (!empty($codesuppr)) {
$total= 0;
$nbc = 0;
$codeliste = array();
foreach($codesuppr AS $code_barre) {
if(count($codeliste) < 500 && ($total + count($codeliste)) < count($codesuppr)) {
array_push($codeliste, $bar_code);
}else{
array_push($codeliste, $bar_code);
$req = "DELETE FROM fean WHERE bar_code IN ('".implode("','",$codeliste)."')";
if($connexion->exec($req)) {
$nbc++;
}else{
echo "Fail at DELETE fean";
}
$total .= count($codeliste);
$codeliste = array();
}
}
echo "Success delete Ean not export";
}
}else{
echo "codeliste is empty<br/>";
}
EDIT3 : After looking mysql, it's seems Replace send too many request at mysql who send back : Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away', and finish in sleep command.
I'm creating PHP API for my Android application which will be used to scan QR codes. Part of that API is checking if scanned code is valid and can be scanned in a certain moment.
Whole checking part is a stored procedure in MariaDB database which is just executed by PHP script. Execution part in PHP is looking like this:
$sql = "CALL someProcedure('qr_code', #out); ";
$sql .= "SELECT #out AS `out`;";
if($conn->multi_query($sql)) {
while ($conn->more_results()) {
$conn->next_result();
}
$rs = $conn->store_result();
$row = $rs->fetch_assoc();
$odp = $row['out'];
if (!empty($rs)) {
$response['success'] = 1;
$response['message'] = $odp;
echo json_encode($response);
$rs->free();
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}
There are 4 results of that stored procedure:
scanned code doesn't exist,
scanned code is not an package (it is an articles code)
scanned code cannot be delivered just yet
scanning was successful
Now, when there is something wrong with the code, PHP part executes without a problem but if scanning is successful I would get a timeout (doesn't matter if it's default 30 seconds or 5 minutes).
The reason there is a timeout (I think) is that when scanning is successful there are some loops executed in Stored Procedure which may be returned in resultsets and choke PHP script ALTHOUGH when I execute that Stored Procedure in DBeaver (with exact same query as in PHP) there is no problem.
So, my question is what I can do about it? Removing the while loop in PHP script above makes the script execute without a problem (but I can't get the out parameter value.
Why not do two queries instead of one multi-query?
This is a respond to a comment by Rick James
Here's modified code:
$sql = "CALL ".$storedProcedure."(".$columns."); ";
$sql2 = "SELECT #out AS `out`;";
if($conn->query($sql)) {
if($rs = $conn->query($sql2)) {
$row = $rs->fetch_assoc();
$odp = $row;
if (!empty($odp)) {
$response['success'] = 1;
$response['message'] = $odp;
echo json_encode($response);
$rs->free();
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}
And mysql error while executing the script:
{"success":0,"message":"Commands out of sync; you can't run this command now"}
The problem is when executing the second query.
I finally got it. All I had to do is to store results in every while loop iteration.
Here's how it looks now.
$sql = "CALL someProcedure('qr_code', #out); ";
$sql .= "SELECT #out AS `out`;";
if($conn->multi_query($sql)) {
while ($conn->more_results()) {
$rs = $conn->store_result();
$conn->next_result();
}
$rs = $conn->store_result();
$row = $rs->fetch_assoc();
$odp = $row['out'];
if (!empty($rs)) {
$response['success'] = 1;
$response['message'] = $odp;
echo json_encode($response);
$rs->free();
} else {
$response['success'] = 0;
$response['message'] = mysqli_error($conn);
echo json_encode($response);
}
The data is not inserting into another table, here's the code below :
if (isset($_POST))
{
$job = $_POST['jobtitle'];
$dur = $_POST['duration'];
$deg = $_POST['requireddegree'];
$exp = $_POST['experiance'];
$sal = $_POST['salary'];
$mark = $_POST['marks'];
if ( !empty($job) && !empty($dur) && !empty($deg) && !empty($exp) && !empty($sal) && !empty($mark))
{
$dur = mysql_real_escape_string($dur);
$deg= mysql_real_escape_string($deg);
$exp = mysql_real_escape_string($exp);
$sal = mysql_real_escape_string($sal);
$mark = mysql_real_escape_string($mark);
$job = mysql_real_escape_string($job);
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('".$dur."','".$deg."','".$exp."','".$sal."','".$mark."','".$job."') ";
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
With this it gives me server error or there was an error in CGI script.But when I write the variables in this form '$dur' instead of '".$dur." then the else conditon runs after insert query and displays data is not inserted.
However, i have written the same logic while inserting data in my another table and it inserts successfully.But there I put '$dur'.
I can't find the problem.Will be glad for your suggestions :)
I can't seem to find any other error by seeing this code expect for
$query="INSERT INTO jobposting (duration,degree,experiance,salary,marks,Jobtitle) VALUES ('$dur','$deg','$exp','$sal','$mark','$job') ";
//Use ".$job." only for stuff like '".md5($_POST['password'])."' otherwise this creates problem some times.
// Adding this always helps
if(!mysqli_query($con,$query))
{
die('error'.mysqli_error($con));
}
// in $con = $con=mysqli_connect("localhost","root","");
else
{
if ($query_run= mysql_query($query))
{
header('location : Main.html');
}
else
{
echo ' Data not Inserted! ';
}
}
I think by making these changes and making sure that your db name and other basic stuff are correct then you should be good to go otherwise, specify your exact error.
I have this PHP code:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s'",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
But this only returns the user that matches the name exactly.
I'd like to return all users containing that name string, for example:
dani -> daniel, dani_56, dani563, elnenedani, ...
It is usually done by putting in PHP: %dani% but as I have put the %s to grab the variable $user, I do not know how to put it.
Any idea?
It is not a great Question. If you have searched well in Stackoverflow you would have go it the answer.. As you asked the Question the answer is.. Instead of Equal use LIKE:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username LIKE %'%s'%",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
It seems the PHP code and DB is working well. Checkout the below links for the error:
iOS 5 JSON Parsing Results in Cocoa Error 3840
Cocoa error 3840 using JSON (iOS)
The Operation couldn't be completed. (Cocoa error: 3840.)
Cocoa Error 3840 - NSJSONSerialization
You should use the LIKE syntax. Make sure to include % to indicate wildcards:
query('SELECT IdUser, username FROM login
WHERE username LIKE "%' . $user . '%"')
My query() function is
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
I do not get fixed. This code is for an ios app that uses AFNetworking, might please that helps you know what happens because I do not get it
This question already has answers here:
How to prevent duplicate usernames when people register?
(4 answers)
Closed 7 months ago.
I am trying to create a user login/creation script in PHP and would like to know the best way to check if a username exists when creating a user. At the moment, I have the following code:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$this->users = $server->query("SELECT * FROM user_list");
while ($check = mysql_fetch_array($this->users) {
if ($check['uname'] == $uname) {
What I'm not sure about is the best logic for doing this. I was thinking of adding a boolean variable to do something like (after the if statement):
$boolean = true;
}
if ($boolean) {
echo "User already exists!";
}
else {
$server->query("INSERT USER INTO TABLE");
echo "User added Successfully";
}
But this seems a little inefficient - is there a more efficient way to do this? Sorry if this has a basic solution - I'm a relatively new PHP programmer.
Use the WHERE clause to get only rows with the given user name:
"SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'"
Then check if the query results in selecting any rows (either 0 or 1 row) with MySQLi_Result::num_rows:
function createUser($uname,$pword) {
$server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$result = $server->query("SELECT * FROM user_list WHERE uname='".$server->real_escape_string($uname)."'");
if ($result->num_rows() === 0) {
if ($server->query("INSERT INTO user_list (uname) VALUES ('".$server->real_escape_string($uname)."'")) {
echo "User added Successfully";
} else {
echo "Error while adding user!";
}
} else {
echo "User already exists!";
}
}
This basically involves doing a query, usually during validation, before inserting the member into the database.
<?php
$errors = array();
$alerts = array();
if (isset($_POST['register'])) {
$pdo = new PDO('[dsn]', '[user]', '[pass]');
// first, check user name has not already been taken
$sql = "SELECT COUNT(*) AS count FROM user_list WHERE uname = ?";
$smt = $pdo->prepare($sql);
$smt->execute(array($_POST['uname']));
$row = $smt->fetch(PDO::FETCH_ASSOC);
if (intval($row['count']) > 0) {
$errors[] = "User name " . htmlspecialchars($_POST['uname']) . " has already been taken.";
}
// continue if there are no errors
if (count($errors)==0) {
$sql = "INSERT INTO user_list ([fields]) VALUES ([values])";
$res = $pdo->exec($sql);
if ($res==1) {
$alerts[] = "Member successfully added.";
} else {
$errors[] = "There was an error adding the member.";
}
}
}
The above example uses PHP's PDO, so change the syntax to use whatever database abstraction you use.