I am trying to pass a value from a select into an update script. I have a page that keeps a members information. I would like to keep the user name and password on a different table. However I am having problems getting the id from the member table to pass to the user id table. Here is what I am doing. The first query is working fine and adding the member information to the member table. It is where I try to do the select and the second update is where I am having problems.
$user_id;
$sql = "INSERT INTO member_contact (mem_first_name, mem_last_name, mem_address_1, mem_address_2, mem_city, mem_state, mem_zip, mem_phone, mem_email)
VALUES ('$_POST[mem_fn]','$_POST[mem_ln]','$_POST[mem_add1]','$_POST[mem_add2]','$_POST[mem_city]','$_POST[mem_st]','$_POST[mem_zip]','$_POST[mem_ph]','$_POST[mem_email]')";
if ($conn->query($sql) === TRUE) {
//echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$selsql = "select mem_id into $user_id from member_contact
where mem_first_name = '$_POST[mem_fn]'
and mem_last_name = '$_POST[mem_ln]'";
if ($conn->query($selsql) === TRUE) {
echo 'mem_id';
} else {
echo "Error: " . $selsql . "<br>" . $conn->error;
}
$insql = "insert into user_info (mem_id, user_id, user_pass)
values('$user_id','$_post[us_id]','$_post[us_pass]')";
if ($conn->query($insql) === TRUE) {
echo 'User name added';
} else {
echo "Error: " . $insql . "<br>" . $conn->error;
}
$conn->close();
Here is the error I am getting with this code.
Error: select mem_id into from member_contact where mem_first_name = 'Andy' and mem_last_name = 'D'
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 'from member_contact where mem_first_name = 'Andy' and mem_last_name = 'D'' at line 1User name added
Thanks for any help.
Related
I am trying to code a little log thing for my Home automations script but then I got this error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 2
My SQL is:
INSERT INTO
logsa (timeb, msg, actionb)
VALUES
('12-05-2018 02:29:38pm',
'Succesfully send a trigger to https://maker.ifttt.com/trigger/test/with/key/xxxxxxxxxxxxxxxxxxxxxxxx With name test',
'https://maker.ifttt.com/trigger/test/with/key/xxxxxxxxxxxxxxxxxxxxxxxx'
and my code is:
$logmsg = ("Succesfully send a trigger to " . $row["actiona"] . " With name " . $row["namea"]);
date_default_timezone_set("Europe/Stockholm");
$date = date("d-m-Y");
$time = date("h:i:sa");
$fulldate = ($date . " " . $time);
$actiona = $row["actiona"];
$sql = "INSERT INTO logsa (timeb, msg, actionb)
VALUES ('$fulldate', '$logmsg', '$actiona'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Change the timeb data value $fulldate to use a valid date time format like this
$fulldate = date('Y-m-d H:i:s');
MySQL and mariaDB expect DATETIME columns to be stored in a very specific format and yours was invalid.
Also you should be using prepared and parametrised queries [link] to avoid SQL Injection attacks like this
$logmsg = ("Succesfully send a trigger to " .
$row["actiona"] .
" With name " .
$row["namea"]);
date_default_timezone_set("Europe/Stockholm");
$fulldate = date('Y-m-d H:i:s');
$actiona = $row["actiona"];
$sql = "INSERT INTO logsa (timeb, msg, actionb) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sss', $fulldate, $logmsg, $actiona );
$result = $stmt->execute();
if ($result) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
I have two table in MySql, which are table 1 and table 2. As I want to link table 1 to 2 via userID. However, the funciton I have come out is not working.
MySQl tables are below:
In my case, userId will be the foreign key to link these 2 tables.
However, my functions are not working.
This is my function below:
function insert() {
function adduserdetails($con, $accountId, $name, $contact) {
$query = "insert into userdetails(accountId,name,contact)
values('$accountId','$name','$contact')";
//echo "{$sqlString}";
$insertResult = mysqli_query($con, $query);
if ($insertResult) {
echo " Applicant Detail Added !<br />";
echo "<a href='index.php'>Back to Home</a>";
} else {
echo " Error !";
echo "{$query}";
//header('Location: post.php');
}
}
}
if ($con->query($query) === TRUE) {
$last_id = $con->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $query . "<br>" . $con->error;
}
function adduseremployment($con,$last_id,$occupationMain,$comapny){
$query1 = "insert into useremployment(userId,Occupation,company)
values('$last_id',$occupationMain','$comapny')";
//echo "{$sqlString}";
$insertResult = mysqli_query($con, $query1);
if($insertResult){
echo " Applicant Detail Added !<br />";
echo "<a href='index.php'>Back to Home</a>";
}
else {
echo " Error !";
echo "{$query1}";
//header('Location: post.php');
}
}
You have vertical table.
Check below code,
Be remember to prepare statement.
<?php
function addUser(){
// parent table.
$queryParent = ''; // Your userdetails table insert query
$insertResult = mysqli_query($con, $queryParent);
$userId = mysqli_insert_id($con); // This is your last inserted userId.
// child table.
$queryChild = ''; // Your useremployment table insert query with userId.
$insertResult = mysqli_query($con, $queryChild);
}
?>
your Query is wrong, please check this,
$query1 = "insert into useremployment(userId,occupation,company)
values('$last_id',$occupationMain','$comapny')";
you have to store record on userId as a refrence not to "accountID".
hope it helps,
In second insert you are using wrong column name (userID and not accountID)
$query1 = "insert into useremployment(userID,Occupation,company)
^^^^^^ here
values('$last_id',$occupationMain','$comapny')";
and in function signature and body you have comapny (could be you want company)
Hi to everyone i have a problemn with a query in PHP to Update records.
<?php
include('../webcgo/script/cox.php');
$query = $cox->query("SELECT cf_id FROM offerte;");
while ($idx = mysqli_fetch_array($query)) {
$check = '<button class="uk-button" onclick="location.href=\'http://localhost/chartscript/remRegola.php?dis=2&id=' . $idx['cf_id'] . '\'">OK</button>';
$query_check = 'UPDATE offerte SET check=\'' . $check . '\' WHERE cf_id=' . $idx['cf_id'].';';
if ($queryx = $cox->query($query_check) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $cox->error;
}
}
mysqli_close($cox);?>
The result:
Error updating record: 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 'check='
check is a MySQL reserved keyword. If you're going to use it in your query you must wrap it in backticks:
$query_check = 'UPDATE agoragroup_chronoforms_data_inserimento_offerte_prod SET `check`=\'' . $check . '\' WHERE cf_id=' . $idx['cf_id'].';';
I am trying to move information from Table A to Table B with the following code. in the same time I want to delete the row in table B once information is moved to table A
//Move from table A to table B
$sql = "insert into del_ussd_members SELECT * FROM members WHERE
member_id='$member_id'";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
print_r($_POST);
echo "\n" . mysql_error($con); echo "mysql err no : " .
mysql_errno($con);
}
//Delete from members
$sql2 = "DELETE FROM members WHERE member_id='$member_id'";
if (mysql_query($sql1, $con)) {
$insertSuccessful = true;
} else {
echo $sql1;
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
The move is happening no problem but the delete function gives me the following error
Query was emptymysql err no : 1065
Even if I run the string on its own I get the same error
Replace
if (mysql_query($sql1, $con)) { //because $sql1 doesn't exist as per your code.
with
if (mysql_query($sql2, $con)) {
You should first change mysql_* functions to mysqli or PDO. Because the whole mysql_* functions will be deprecated in the coming versions.
There is no $sql1 variable in your code so you can't use it. You probably wanted to use $sql2.
Also, think about moving to PDO or mysqli_*, because mysql_* is deprecated and will be removed from PHP.
Next thing is that your first query is incorrect. Split it to two separated queries.
you need to change $sql1 to $sql2 in second query.
//Delete from members
$sql2 = "DELETE FROM members WHERE member_id='$member_id'";
if (mysql_query($sql2, $con)) {
Copy Paste:
//Move from table A to table B
$sql = "insert into del_ussd_members SELECT * FROM members WHERE
member_id='$member_id'";
if (mysql_query($sql, $con)) {
$insertSuccessful = true;
} else {
echo $sql;
print_r($_POST);
echo "\n" . mysql_error($con); echo "mysql err no : " .
mysql_errno($con);
}
//Delete from members
$sql2 = "DELETE FROM members WHERE member_id='$member_id'";
if (mysql_query($sql2, $con)) {
$insertSuccessful = true;
} else {
echo $sql2;
echo "\n" . mysql_error($con);
echo "mysql err no : " . mysql_errno($con);
}
Basically I have edited the "new_topic" page in my generic forum so that the user can select the category of the post from a drop down list, rather than goto the category first and going to new topic, what I am trying to do now is when the thread is created, rather than jumping to the standard "your new thread was created here" it redirect to the category the topic was made under.
I tried using
header( "Location: category.php?id='. $topic_cat . '" );
But header was already being used elsewhere.
So I found a meta refresh that works to an extent..
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id='. $topic_cat .'>";
But it redirects to "category.phpid=" and outputs the following message..
The category could not be displayed, please try again later.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 '' at line 8
Is there anyway I can make the page jump to the category that is only being defined in the submit function itself? Thanks for any help.
EDIT: would using "if" functions work to define the redirect? ie. if topic_cat 2 is selected in the form redirect to category.phpid=2??
Sorry I am very new to PHP and still trying to get my head around it all :(
Here is the topic creation page in it's entirety
<?php
//create_topic.php
include 'connect.php';
if($_SESSION['signed_in'] == false)
{
//the user is not signed in
echo 'Sorry, you have to be signed in to create a topic.';
}
else
{
//the user is signed in
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
//the form hasn't been posted yet, display it
//retrieve the categories from the database for use in the dropdown
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$result = mysql_query($sql);
if(!$result)
{
//the query failed, uh-oh :-(
echo 'Error while selecting from database. Please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
//there are no categories, so a topic can't be posted
if($_SESSION['user_level'] == 1)
{
echo 'You have not created categories yet.';
}
else
{
echo 'Before you can post a topic, you must wait for an admin to create some categories.';
}
}
else
{
echo '<form method="post" action="">';
echo '<select name="topic_cat">';
while($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select><br />';
echo '<textarea name="post_content" /></textarea><br /><br />
<input type="submit" value="Create topic" />
</form>';
}
}
}
else
{
//start the transaction
$query = "BEGIN WORK;";
$result = mysql_query($query);
if(!$result)
{
//Damn! the query failed, quit
echo 'An error occured while creating your topic. Please try again later.';
}
else
{
//the form has been posted, so save it
//insert the topic into the topics table first, then we'll save the post into the posts table
$sql = "INSERT INTO
topics(topic_subject,
topic_date,
topic_cat,
topic_by)
VALUES('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . mysql_real_escape_string($_POST['topic_cat']) . ",
" . $_SESSION['user_id'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your data. Please try again later.<br /><br />' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicid = mysql_insert_id();
$sql = "INSERT INTO
posts(post_content,
post_date,
post_topic,
post_by)
VALUES
('" . mysql_real_escape_string($_POST['post_content']) . "',
NOW(),
" . $topicid . ",
" . $_SESSION['user_id'] . "
)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'An error occured while inserting your post. Please try again later.<br /><br />' . mysql_error();
$sql = "ROLLBACK;";
$result = mysql_query($sql);
}
else
{
$sql = "COMMIT;";
$result = mysql_query($sql);
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id=". $topic_cat ."'>";
}
}
}
}
}
; ?>
echo "<META HTTP-EQUIV='Refresh' Content='0; URL=/category.php?id=" . $topic_cat . "'>";
That should work. You needed to put double quotation-marks outside the . $topic_cat . variable like so; " . $topic_cat . "