MySQL Query max issue - php

I have a query that that works fine as long as there exists values in it after the WHERE condition is called. However, in some cases the query is empty because no values = '$project_id'. In this scenario it enters a blank field to the table. I would like to enter 1 by default if no values meet the WHERE condition.
Here is my query
$query =
"INSERT INTO tapp_contact_list
(id, location)
SELECT (MAX(id)+1), '$location'
FROM tapp_contact_list
WHERE meeting_project_id = '$project_id'
";
Any help is gladly appreciated!

Try this.
$query =
"INSERT INTO tapp_contact_list
(id, location)
SELECT COALESCE( (MAX(id)+1), 1 ) , '$location'
FROM tapp_contact_list
WHERE meeting_project_id = '$project_id'
";
For more details check this function.
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce

Related

Is there a way to choose an ID randomly to go into a database

I am making a car dealership booking form and I need to select a staff member at random to go on the test drive
I've tried mt_rand() but I think I'm putting it in the wrong place
````````````````````````````````````
$sql = "INSERT INTO bookingcars (BookingStart, BookingEnd, BookingDate, MemberReference, ActivityID staffID) VALUES ('$timeStart', '$timeEnd', '$startDate', '$memberReference', '$activity', '$mt_rand(1, 4)staffID'";
````````````````````````````````````
while you could build it in the query, its little cleaner and easier to debug if you do something like:
$staff=rand(1,4).'staffID'; // assume you wanted 1staffID .. ?
//or did you just want $staff=rand(1,4);
$sql = "INSERT INTO bookingcars (BookingStart, BookingEnd, BookingDate, MemberReference, ActivityID, staffID) VALUES ('$timeStart', '$timeEnd', '$startDate', '$memberReference', '$activity', '$staff')";
Another way would be in your query values to add a subquery like ,...) VALUES (..., (SELECT DISTINCT (Id) FROM stalesstafftable order by Rand() limit 1))

PHP MySQL Insert Query From Multiple Tables into two tables

I've table like this :
tb_users
id, name, pin_number
tb_attendance
pin, date_time, user_id
i've created simple query for tb_attendace like this :
$sql = "INSERT INTO tb_attendance
( pin, date_time)
values
('$PIN', '$DateTime')";
i want to insert colum user_id from tb_users where tb_users.pin_number = tb_attendance.pin
in mysql command i've success run this :
INSERT INTO tb_attendance (pin, date_time, entry_by)
SELECT pin, date_time, tb_users.id
FROM tb_attendance , tb_users
WHERE tb_attendance.pin = tb_users.pin_number
but i don't know how to create this query into php script.
can some one help me to complete the php script ?
I'm not sure why you need both the pin and user id, if you can just use JOIN to get the PIN.
The query that you want looks something like this:
INSERT INTO tb_attendance (pin, date_time, entry_by)
SELECT $PIN, $DATE_TIME, u.id
FROM tb_users u
WHERE u.pin_number = $PIN;
I would advise you to use query parameters, and not to insert the parameter values directly into the SQL string. That is dangerous -- both in terms of creating a SQL syntax error and in terms of security.

insert records from one table to another

Hi I am trying to add records from one table to another, once i have added a 'user' record, the table that is being selected contains rows of available security options, and the table that is being inserted to is the child table for the user, detailing security options.
I cam across this code in an earlier post, which i am sure works nicely, however i am trying to modify it so that the values from statement, includes two parts, one from the select query and one which is the key from the master record.#
This is the original code I found from this site:
INSERT INTO def (catid, title, page, publish)
SELECT catid, title, 'page','yes' from `abc`
And this is what I am trying to do with it:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('".$keys["UserPk"]."', SELECT ModulePk from Global_Modules)";
CustomQuery($sql);
And this is the error I am getting:
INSERT INTO Link_UserSecurity (UserFk, ModuleFk) values ('4', SELECT
ModulePk from Global_Modules)
See screenshot for further detail
Obviously I am not concating the from statement properly, but would appreciate any help?
You can insert the $keys["UserPk"] variable as if it were a constant in the SQL:
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Do note that $keys["UserPk"] must be escaped before adding it into the query. In PDO, it would look like this:
$keys["UserPk"] = $pdo->quote($keys["UserPk"]);
$sql = "INSERT INTO Link_UserSecurity (UserFk, ModuleFk) SELECT '{$keys["UserPk"]}', ModulePk from Global_Modules";
Could be a problem related to the double quotes sequence
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
values ('". $keys['UserPk']. "', SELECT ModulePk from Global_Modules)";
but you could use also a select insert
"INSERT INTO Link_UserSecurity (UserFk, ModuleFk)
SELECT '" . $keys['UserPk']. "' , ModulePk from Global_Modules)";
Adding only new and unique records from one table to another. Limiting is a good idea to prevent it from timeout. It can be run several times until all the records copied.
First, select the latest record ID from the table to be copied:
SET #lastcopied =
(SELECT
IF(MAX(a.exp_inotech_id)>0, MAX(a.exp_inotech_id), 0) AS lastcopied
FROM
kll_export_to a
WHERE exp_tezgah = 'A2015-0056');
Then, select and add the records to the destination table:
INSERT INTO kll_export_to
(SELECT * FROM
kll_export_from f
GROUP BY f.exp_inotech_id
HAVING COUNT(f.exp_inotech_id) = 1 AND exp_tezgah = 'A2015-0056' AND f.exp_inotech_id > #lastcopied
ORDER BY exp_inotech_id
LIMIT 1000);

Insert Data into MySQL using php

$sql = 'INSERT INTO photo '.
'(id,cid, path,date) '.
'VALUES (,`$cid`, `$new`,)';
There are four columns in the table, "photo".
1) id - auto increment
2) cid - $cid
3) path - $new
4) time - timestamp
Now I want to insert new data only to the cid and path fields. How can I do it with the above mentioned code
Try this:
//$con = you connection
$sql = "INSERT INTO photo (cid, path) VALUES ('$cid', '$new')";
mysqli_query($con, $sql);
this is as simple try this
$sql = "INSERT INTO photo (`cid`, `path`) VALUES ('$cid', '$new')";
Try this, if you know the value of id and date column value then pass it, other wise you just skip it or atlast pass the default value.
$sql = "INSERT INTO photo (cid, path,`date`) VALUES ('$cid', '$new',now())";
$sql = "INSERT INTO photo (cid, path,`date`) VALUES ('$cid', '$new',CURRENT_TIMESTAMP)";
1st of all... this is how you do debugging:
Run the query in phpmyadmin (echo query from php then run in phpmyadmin to see exactly what error you are getting, then adjust and test until it works properly
2nd: The ID. Either you lose it, like other people suggested above or you set it NULL and it gets auto incremented if it's set right in the schema.
I'm not trying to just give you a solution, i'm trying to get you some information, so you don't have to ask the next time.
$sql = "INSERT INTO photo (id,cid, path,date) VALUES (NULL,'".$cid."', '".$new."',now())";
mysqli_query($con, $sql);
You have some errors in your query
You have used tick mark around the variables which is invalid
Unwanted , at starting while entering values
This is not an error, but an advice:There is no need for breaking a query into several parts until it is large.
For inserting only cid and path Do like this
$sql = "INSERT INTO photo (cid, path) VALUES ('".$cid."', '".$new."')";

Why do I get a 500 error? (MySQL php)

<html>
<head>
HTML CODE
<?
$username="xxxxxx";
$password="xxxxxx";
$database="xxxxxx";
mysql_connect(localhost,$username,$password);
$escape = "INSERT INTO monster VALUES ('',$_POST["name"],$_POST["soort"])";
$escape2 = "DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL";
$query=mysql_real_escape_string($escape);
$query2=mysql_real_escape_string($escape2);
#mysql_select_db($database) or die("MySQL error: Kan inte ansluta till databasen.");
mysql_close();
?>
</body>
</html>
Every time i run this(from another file, containing the name and soort post's) I get an 500 internal server error. First I figured that the queries may be the problem, but they don't even get executed. However, i tried to escape the queries. But still error.
What is wrong with this code? (note: $escape2 is some code i found that removes duplicates in the database. But i don't really know how to format it so that it can be used through php.)
Use something like below...
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Please do not insert values without escaping.
problem in insert into statement
it should be
$escape = "INSERT INTO monster VALUES ('',".$_POST['name'].",".$_POST['soort'].")";
it is preferable to write colums name while writing insert queries
if column contains string values like VARCHAR or TEXT then use quoted_printable_decode
pass null if column is autoincrement
insert statment
$escape = "INSERT INTO monster (col1, col2, col3) VALUES (NULL,'".$_POST['name']."',".$_POST['soort'].")";
or
$escape = "INSERT INTO monster (col2, col3) VALUES ('".$_POST['name']."',".$_POST['soort'].")";
It looks like you need something like this:
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
Also I would suggest to use prepared statements because it is bad experience to build queries.
First of all I have cool proposition for you. What do you say about some advanced PHP? One step further into great world of safe PHP + MySQL apps?
Introducting to you a PDO. (I know this is not answer to your question but you can consider it). Example of use on your queries:
$db = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
$insertQuery = $db->prepare('INSERT INTO monster VALUES ("", :name, :soort)');
$deleteQuery = $db->prepare('DELETE monster FROM monster LEFT OUTER JOIN (
SELECT MIN( ID ) AS ID, NAME, PREF
FROM monster
GROUP BY NAME, PREF
) AS KeepRows ON monster.ID = KeepRows.ID
WHERE KeepRows.ID IS NULL');
//to execute query:
$deleteQuery->execute();
//or with params:
$insertQuery->execute(array(
':name' => $_POST['name'],
':soort' => $_POST['soort'],
));
Cool, huh? There is more... Now according to your problem it could be everything (as we don't have error log) but my guess is:
Try to use <?php instead of <?
$escape = "INSERT INTO monster VALUES ('',{$_POST["name"]},{$_POST["soort"]})";
EDIT:
As you provided error log - now I'm sure that problem is in $escape query. It's because you used $escape = " <- and then $_POST["name"] so there was a collision of " (if I can say so).
Try this:
Whenever you insert string type of values in the database using query it has to pass in the quote format. So you just need to change your insert query here.
$query = "INSERT INTO monster VALUES ('', '".$_POST["name"]."', '".$_POST["soort"]."')";
write query like this.
-
Thanks

Categories