PHP move information between SQL Tables - php

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);
}

Related

How to use msqli multi_query fuction inside a transaction

I will be running every midnight a cron job (php script) to copy all the records from one table to another and then delete them from the first one table.
Here is what I have for now:
<?php
include('conf/conn.php');
$result = mysqli_query($conn, "SHOW TABLES FROM mydb LIKE '%salon%'");
while($table = mysqli_fetch_array($result)) {
$tableToCopy = $table[0];
mysqli_begin_transaction($conn, MYSQLI_TRANS_START_READ_ONLY);
mysqli_query($conn, "INSERT INTO history SELECT * FROM $tableToCopy");
// Here is where I'm stuck
// $sql = "INSERT INTO history SELECT * FROM $tableToCopy; ";
// $sql.= "DELETE FROM $tableToCopy; ";
// if (!$mysqli->multi_query($sql)) {
// echo "Both executions failed: (" . $mysqli->errno . ") " . $mysqli->error;
// }
mysqli_commit($conn);
mysqli_close($conn);
if (!mysqli_commit($conn)) {
echo 'Failed.';
echo '<br>';
} else {
echo 'Successful';
echo '<br>';
}
}
?>
I can't find how to make more than one query inside a transaction. Can someone please guide me? Thanks in advance.

multi word values gives error in insert query

i am trying to insert a row in table using query->
INSERT INTO organizers(username, hotel, city, state, address, type, price1, price2, contact) VALUES ('nitin','moxvox','jodhpur','rajasthan','shastri circle','1','500','0','1000');
this query works fine. but when i try to give multi word values like username as 'nitin gehlot' instead of 'nitin': the query fails and returns the error part of response.
i am not much familiar with php: please help me.
php code->
$connect= mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$sqlq=$_GET['query'];
//test
if(mysqli_connect_errno()) {
die("data base connection failed: ".
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
$query = "$sqlq";
$result = mysqli_query($connect,$query);
if(!$result)
{
die("query is faild" . mysql_error);
}
if(strpos($query,'INSERT')!==false)
echo mysqli_insert_id($connect);
else{
echo ' {"result" : 1, "message" : [';$i=1;
while($row = mysqli_fetch_object($result))
{
if($i==1){$i=0;}
else echo',';
$j = json_encode($row);
echo $j;
}
echo ']}';
}
Thanks in advance.

store data to 2 tables with foreign key in MySql php

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)

Getting a Value to use in an update script in php

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.

PHP/Mysql Create thread then redirect to forum category

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 . "

Categories