insert with a select statement and php variables in 1 MySQL query - php

i have something like this to insert data from a form to my MySQL table. is my use of select statements in the insert valid? please enlighten me.
if(isset($_POST['date']) && isset($_POST['docName']) && isset($_POST['docSpec']) && isset($_POST['time']) && isset($_POST['symptoms']) )
{
$nameOfUser = $_COOKIE['userlogin'];
$docName = $_POST['docName'];
$date = $_POST['date'];
$symptoms = $_POST['symptoms'];
$time = date('H:i:s',strtotime($_POST['time']));
$id = mt_rand(1000,9999); //generate random appointment id
$insertQuery = "insert into appointment values
($id,(select doctorid from doctors where doctorName like '$docName' ),
$date,$symptoms,
(select patientid from patient where patientFName like '$nameOfUser'), $time)";
if(mysqli_query($conn,$insertQuery)===true)
{
echo "<script>alert('success');</script>";
}
else
{
die('Invalid query: ' . mysql_error());
$message .= 'Whole query: ' . $query;
die($message);
}
}
it says invalid query. the columns in the insert statement is already in right order. can anyone help me?

You have to specify the columns that you are inserting into -
insert into appointment (col1, col2, col3, ...) values
($id,(select doctorid from doctors where doctorName like '$docName' ), $date,$symptoms,(select patientid from patient where patientFName like '$nameOfUser'),$time)";
It looks like you have 6 columns.
EDIT: This syntax may help to clear things up -
$insertQuery = "INSERT INTO `appointment` (`col1`, `col2`, `col3`,`col4`,`col5`,`col6`) ";
$insertQuery .= "VALUES (";
$insertQuery .= "'" . $id . "'";
$insertQuery .= ", '" . "(SELECT `doctorid` FROM `doctors` WHERE `doctorName` LIKE '%" . $docName . "%')" . "'";
$insertQuery .= ", '" . $date . "'";
$insertQuery .= ", '" . $symptoms . "'";
$insertQuery .= ", '" . "(SELECT `patientid` FROM `patient` WHERE `patientName` LIKE '%" . $nameOfUser . "%')" . "'";
$insertQuery .= ", '" . $time . "'";
$insertQuery .= ")";
You're also using LIKE without giving it the chance to find other elements because you're not using wildcards.

Related

How do you pass something like "+ interval 4" to the bindParam

I am trying to pass a variable that looks like this "+ interval 4" or "- interval 5" to this PDO statement.
$query = "INSERT INTO
" . $this->table_name . " (employee_id, work_date)
SELECT DISTINCT emp_num,
CURDATE() :test DAY FROM " . $this->table_name3 . "";
My bindParam
$stmt->bindParam(":test", $this->interval);
I not sure if I should be using bindValue having a hard time figuring this out.
This works fine but i know it is not right
$query = "INSERT INTO
" . $this->table_name . " (employee_id, work_date)
SELECT DISTINCT emp_num,
CURDATE() " . $this->interval . " DAY FROM " . $this->table_name3 . "";
and here is the whole function if that helps
function sqlbuild(){
$query = "INSERT INTO
" . $this->table_name . " (employee_id, work_date)
SELECT DISTINCT emp_num,
CURDATE() " . $this->interval . " DAY FROM " . $this->table_name3 . "";
$stmt = $this->conn->prepare( $query );
echo json_encode($stmt);
$stmt->bindParam(":test", $this->interval);
//$stmt->bindParam(1, $this->interval);
echo json_encode($this-> interval);
if($stmt->execute()){
return true;
}else{
return false;
}
}

insert into with multiple rows not working

i can't make this insert into work. can someone tell me where i'm doing wrong?
$id_application = 1;
foreach ($array_account as $rows) {
$e_mail = $rows["EMAIL"];
$pwd = $rows["PWD"];
$salt = $rows["SALT"];
$values = "(" . $e_mail . ", " .$pwd . ", " .$salt . ", " . $id_application . ")";
$query = "INSERT INTO DBNAME..ACCOUNT (EMAIL, PWD, SALT, ID_APPLICATION) "
. " VALUES " . $values;
$result = sybase_query($query);
}
these are the errors that iget:
Column names are illegal. (severity 15, procedure N/A
The identifier that starts with '...' is too long. Maximum length is 30
The name '...' is illegal in this context. Only constants, constant expressions, or variables
allowed here
i'm able to insert a single row in sybase central like:
insert into DBNAME..ACCOUNT (EMAIL, PWD, SALT, ID_APPLICATION)
select EMAIL, PWD, SALT, 3 from ACCOUNT where ID = 10 go
Do this $values = "('" . $e_mail . "', '" .$pwd . "', '" .$salt . "', '" . $id_application . "')";

What is wrong with this SQL IF Statement?

so I am building a search script and meed to pass on two variables, but first I want to make sure that the SQL QUery is correct so I am hard-coding the variable for now. So my variable is
$comma_separated = "'Alberta','Ontario'";
This is getting passed through to the query, which looks like this:
$sql = "SELECT * FROM persons WHERE 1=1";
if ($firstname)
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";
if ($surname)
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";
if ($province)
$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' WHERE province IN ($comma_separated)";
$sql .= " ORDER BY surname";
and then when the query runs, I get this message:
cannot run the query because: 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 'WHERE province IN ('Alberta','Ontario') ORDER BY surname LIMIT 0, 5' at line 1
But to me the query looks right, what am I missing here?
Thanks in advance.
You can't have WHERE in there twice. You also seem to be trying to filter on province values in two different ways. Based on the assumption that $province will always be an array of values (even if only a single value is given), you can try this:
$sql = "SELECT * FROM persons WHERE 1=1";
if (!empty($firstname)) {
$sql .= " AND firstname='" . mysqli_real_escape_string($mysqli,$firstname) . "'";
}
if (!empty($surname)) {
$sql .= " AND surname='" . mysqli_real_escape_string($mysqli,$surname) . "'";
}
if (!empty($province)) {
array_walk($province, function($value, $key_not_used) use ($mysqli) {
return mysqli_real_escape_string($mysqli, $value);
});
$sql .= " AND province IN ('" . implode(',', $province) . "')";
}
$sql .= " ORDER BY surname";
Your SQL contains two WHERE's.
SELECT * FROM persons WHERE 1=1
AND firstname='fn'
AND surname='sn'
AND province='p'
WHERE province IN ($comma_separated)
ORDER BY surname
Change the last bit to:
$sql .= " AND province='" . mysqli_real_escape_string($mysqli,$comma_separated) . "' AND province IN ($comma_separated)";
Which becomes:
AND province='p'
AND province IN ('Alberta','Ontario')
Change the last part to:
if ($province)
$sql .= " AND province IN (" . mysqli_real_escape_string($mysqli,$comma_separated) . ")";

How can I get the number of rows in a MySQL table with PHP?

Why is my code returning a 500 Internal Server error on the line $result = mysql_query("SELECT * FROM institutions"); Am I doing something horrifically wrong? All I am trying to do is count the number of rows in a MySQL table (called 'institutions') after I have just added a row to that table.
$institution_sql = "
INSERT INTO `institutions`
(`InstitutionName`, `HeaderPictureID`, `Description`, `DevicesInfo`, `DoingInfo`, `FacebookPage`, `Location`, `TwitterHandle`, `Website`, `CreatedAt`)
VALUES
(" . nz($_POST['TempInstitutionName']) . ", 74, 'N/A', 'N/A', 'N/A', 'N/A', 'On the Internet', 'N/A', 'N/A', NOW())
";
$mysqli->query($institution_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "PASSWORD_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
$result = mysql_query("SELECT * FROM institutions");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";
$insert_sql = "
INSERT INTO `users`
(`Handle`, `Email`, `FirstName`, `LastName`, `InstitutionID`, `TempInstitutionName`, `TwitterHandle`, `ProfilePictureID`, `HeaderPictureID`, `AccountType`, `CreatedAt`)
VALUES
(" . nz($_POST['Handle']) . ", " . nz($_POST['Email']) . ", " . nz($_POST['FirstName']) . ", " . nz($_POST['LastName']) . ", $num_rows, " . nz($_POST['TempInstitutionName']) . ", " . nz($_POST['TwitterHandle']) . ", " . nz('75') . ", " . nz('74') . ", " . nz($_POST['AccountType']) . ",NOW())
";
$mysqli->query($insert_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "EXEC_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
$insertid = $mysqli->insert_id;
$password_sql = "
INSERT INTO `passwords`
(`UserID`)
VALUES
('$insertid')
";
$mysqli->query($password_sql);
if ($mysqli->errno) {
$dbreturn['status'] = "PASSWORD_FAILURE";
} else {
$dbreturn['status'] = "EXEC_SUCCESS";
}
} //todo: use a transaction here
}
your problem is that you mixing MYSQLI with MYSQL
rewrite your code using mysqli
$result = $mysqli->query("SELECT * FROM institutions");
$rows = $result->num_rows ;
// and so on ...
you are connecting via mysqli and then you use mysql in your code.
$result = mysql_query("SELECT count(*) FROM institutions");
This will directly return the number of rows.
This link can detail you
http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html
Use
$result = $mysqli->query($institution_sql);
$result->num_rows;
Or for plain old mysql
$result = mysql_query($institution_sql);
mysql_num_rows($result);
Try this:
$result = mysql_query("SELECT count(*) FROM institutions");
MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/select.html
Also this: http://www.w3schools.com/sql/sql_func_count.asp
SQL COUNT(*) Syntax
The COUNT(*) function returns the number of records in a table:
...also, that should be:
VALUES
('" . nz($_POST['TempInstitutionName']) . "', 74
Note the single quotes [unless the 'nz' function takes care of that].

Insert into mysql and php using array

I have part of the code below:
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO".TBL_USERSDONTPAY."VALUES ($array[\"username\"], $array[\"password\"], '0',$array[\"userid|\"], )";
$second_result = $database->query($second_query);
}
The query doesn't seem to work. Any clues? I think it's a problem with the quotes or something. How can actually pass array elements?
here is my whole code i want to move one row to another table
$q = "SELECT * FROM ".TBL_USERS." WHERE username = '$subuser'";
$result = $database->query($q);
if($result && $result->num_rows == 1){
while($array = $result->fetch_assoc() ){
$second_query = "INSERT INTO" . TBL_USERSDONTPAY . "VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] ."')";
$second_result = $database->query($second_query);
if($second_result){
// it worked!
$q = "DELETE FROM ".TBL_USERS." WHERE username = '$subuser'";
$database->query($q);
}
}
}
You need to clean that query up and remove the final comma.
$second_query = "INSERT INTO " . TBL_USERSDONTPAY . " VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
I see several issues with your query code
escaping of the array indexes in your string:
you can either end the string and concatenate the parts together:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('" . $array['username'] . "', '" . $array['password'] . "', '0', '" . $array['userid'] . "')";
or use the {$var} syntax:
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
missing spaces (see example code above .. you were missing the spaces before and after the table name)
missing field names. your query may work without if you specify all fields in the right order, but will fail misteriously when you alter the table later (e.g. add a field to the table)
$second_query = "INSERT INTO " . TBL_USERSDONTPAY .
" (username, password, foo, user_id)".
" VALUES ('{$array['username']}', '{$array['password']}', '0', '{$array['userid']}')";
please note you should actually insert the correct field names in the second line of my example above. You can find more information on this in the MySQL docs for INSERT

Categories