send json from jquery to php and insert into database - php

I need to insert data from a webpage into a database. I'm using this code to send it to the php file
$.getJSON('./calendar.php?action=save&id=0&start='+ds.getTime()/1000+'&end='+df.getTime()/1000,
{
'body':$('#calendar_new_entry_form_body').val(),
'title':$('#calendar_new_entry_form_title').val()
}
and then I want to insert the 4 fields into a mySQL database. Right now, I can retrieve the data using
$start_date=(int)$_REQUEST['start'] - 60*60;
$data=array(
'title'=>(isset($_REQUEST['title'])?$_REQUEST['title']:''),
'body' =>(isset($_REQUEST['body'])?$_REQUEST['body']:''),
'start'=>date('c',$start_date),
'end' =>date('c',(int)$_REQUEST['end'] - 60*60)
);
Then I save it into a session variable just to see if I am actually recieving it
$id=(int)$_REQUEST['id'];
if($id && isset($_SESSION['calendar'][$id])){
$_SESSION['calendar'][$id]=$data;
}
else{
$id= ++$_SESSION['calendar']['ids'];
$_SESSION['calendar'][$id]=$data;
}
I'm using var_dump on session in another page and the data is going through correctly.
session_start();
var_dump($_SESSION);
echo "<br>";
echo $_SESSION['calendar'][1]['title'];
echo "<br>";
echo $_SESSION['calendar'][1]['start'];
What I can't seem to be able to do, is insert this data into a database. Every time I try to run a query, nothing happens.
The query I'm using is:
$query1 = "INSERT INTO `doc`.`appointment` (`start`, `end`, `title`, `body`) VALUES ('$data['start']', '$data['end']', '$data['title']', '$data['body']');";
$result1 = $con->query($query1);

your query
$query1 = "INSERT INTO `doc`.`appointment` (`start`, `end`, `title`, `body`) VALUES ('$data['start']', '$data['end']', '$data['title']', '$data['body']');";
$result1 = $con->query($query1);
i have corrected it little bit try this
$query1 = "INSERT INTO `doc`.`appointment` (`start`, `end`, `title`, `body`) VALUES (".$data['start'].", ".$data['end'].", ".$data['title'].", ".$data['body'].")";
$result1 = $con->query($query1);

Related

Insert INTO not working

I have a problem with SQL syntax. I have 2 tables and the third table is generated in SQL Workbench (n:m relationship).
My 3rd table has 2 columns product_id and categories_id.
I use this SQL in php my admin to add a new row:
INSERT INTO `products_has_categories` (`products_id`, `categories_id`)
VALUES ('17', '1');
if phpmyadmin, the sql add a new row, with product_id = 17 and categories_id =1.
My problem:
i have a simple php file called test.php looking like:
$connection = mysqli_connect("andrei.local","andrei94ro","masina", "intership");
if(!$connection)
{
echo 'error';
}
$query = "INSERT INTO `products_has_categories` (`products_id`, `categories_id`) VALUES ('17', '1');";
or
$query = "INSERT INTO `products_has_categories` (`products_id`, `categories_id`) VALUES ('17', '1')";
When i run test.php file, the code not working, and no adding new row in SQL table.
Can u help me?
As far I'm concerned, you're not even calling query().
Try this:
$connection = new mysqli("andrei.local","andrei94ro","masina", "intership");
if(!$connection)
{
echo 'error';
} else {
$query = $connection->query("INSERT INTO `products_has_categories` (`products_id`, `categories_id`) VALUES ('17', '1')");
}

Get a row from a database using PHP and mySQL and then edit it

So I'm using php to add or get data from a database. The way I'm trying to do this is to check if there is something there with that title, if there is, edit it, if not, add a new entry. This is the code I'm using:
$SQL_CHECK = "SELECT * FROM `doc`.`appointment` WHERE `title` = '$form_title';";
$checkQ = $con->query($SQL_CHECK);
if(mysqli_num_rows($checkQ)>=1) {
while($t = mysqli_fetch_array($checkQ)){
$editID = $t['id'];
//edit the entry
$query_edit = "UPDATE `doc`.`appointment` SET `title`='$form_title' WHERE `id`=$editID;";
$edit_row = $con->query($query_edit);
}
}elseif(mysqli_num_rows($checkQ)==0){
//add new entry
$query1 = "INSERT INTO `doc`.`appointment` (`start`, `end`, `title`, `body`) VALUES ('$start_date', '$end_date', '$form_title', '$form_body');";
$result1 = $con->query($query1);
}
The problem I have is that, when I run the code, if there already is something there, it runs both queries (it adds a new one and edits the one existing)

selecting mysql database's table in php $query

I am sending from arduino usinh http 1.1 (x-www-form-urlencoded) temperature and humidity readings to mysql database. if I use commented part of the following code, everything works (tab12 is the name of the table in mysql database). But I would like to arduino send the name of the table, so I could use the same add.php file to play with multiple arduinos. The thing is, I don't understand how to correctly put the table name from $tabid=$_POST["tabid"]; to query.
<?php
include("connect.php");
$link=Connection();
$tabid=$_POST["tabid"];
$temp1=$_POST["temp1"];
$hum1=$_POST["hum1"];
// $query = "INSERT INTO `tab12` (`temperature`, `humidity`)
// VALUES ('".$temp1."','".$hum1."')";
$query = "INSERT INTO `"tabid"` (`temperature`, `humidity`)
VALUES ('".$tabid."','".$temp1."','".$hum1."')";
mysql_query($query,$link);
mysql_close($link);
header("Location: index.php");
?>
You would concatenate just as you would with any variable:
$query = "INSERT INTO `" . $tabid . "` (`temperature`, `humidity`)
VALUES ('".$temp1."','".$hum1."')";
In addition your number of columns and values must match.

sql php insert in to table via if statement

simply put my code doesn't seem to be working probably the variables work and echo out its simply the code for insert im doing wrong no error just doesnt insert into the table.. the idea is that it inserts in to a table and replaces the data already in the id selected
if(($_REQUEST['questionbox']=="" )||($_REQUEST['boxA']=="")|| ($_REQUEST['boxB']=="")|| ($_REQUEST['boxC']=="")|| ($_REQUEST['boxD']=="")|| ($_REQUEST['correctbox']==""))
{
echo "must enter data";
}else{
$sql2 = "INSERT INTO `tblas`(`id`, `question`, `A`, `B`, `C`, `D`, `correct`) VALUES ([".$idbox."],[".$questionbox."],[".$boxA."],[".$boxB."],[".$boxC."],[".$boxD."],[".$correctbox."])";
$editquery= mysql_query($sql2, $db);
echo $editquery;
try this query instead of insert query
if(($_REQUEST['questionbox']=="" )||($_REQUEST['boxA']=="")|| ($_REQUEST['boxB']=="")|| ($_REQUEST['boxC']=="")|| ($_REQUEST['boxD']=="")|| ($_REQUEST['correctbox']==""))
{
echo "must enter data";
}else{
$sql2 = "UPDATE tblas SET id='".$idbox."', question = '".$questionbox."', A = '".$boxA."', B = '".$boxB."' ,C = '".$boxC."', D= '".$boxD."' , correct= '".$correctbox."'";
}
echo $editquery;

How can I insert multiple rows into a database using results from another data query and posts from the same page?

I am trying to gather a random amount of members from my database, get their id numbers and use them to insert multiple entries into another table using the ids and some posted info from the same page.
Current (non-working) code:
if($_POST["Submit"] == "Send Mail") {
$rid = $_SESSION["userid"];
//is amount of members sending to
$to = $_POST["credits"];
$messaging = $_POST["message"];
$sub = $_POST["subject"];
///need all ids for amount of membes sending to
$getodds = mysql_query("select Id from `oto_members` ORDER BY RAND() Limit '$to';");
...
///insert a new line for each member sending to using ids from $getodds query
#mysql_query("INSERT INTO `mp_creditmail` (`Id`, `message`, `subject`, `read`) VALUES ('$values', '$messaging', '$sub', no) or die(mysql_error());
}
In SQL can insert multiple records in a table with a query. You can look at the following link. http://dev.mysql.com/doc/refman/5.0/es/insert-select.html
Looking at the example could use the following statement to what you need.
///insert a new line for each member sending to using ids from $getodds query
#mysql_query("INSERT INTO 'mp_creditmail' ('Id', 'message', 'subject', 'read') SELECT oto_members.Id, '$messaging', '$sub', 'no' FROM oto_members ORDER BY RAND() Limit '$to';");
I'm trying to answer your question, but your code/question is a little unclear. I will assume that you want to use the id's obtained in $getodds in your second query where '$values' is. Also, if you are using php version 5 or newer, you should use a non-deprecated query function like mysqli_query()
foreach($getodds as $values) {
#mysql_query("INSERT INTO `mp_creditmail` (`Id`, `message`, `subject`, `read`)
VALUES ($values, $messaging, $sub, 'no')" or die(mysql_error());
}
mysqli_query() would look like this
$link = mysqli_connect("localhost", "my_user", "my_password", "database");
foreach($getodds as $values) {
$query = "INSERT INTO `mp_creditmail` (`Id`, `message`, `subject`, `read`)
VALUES ($values, $messaging, $sub, 'no')";
$result = #mysqli_query($link, $query)
}
Hope this helps. If not, try to clarify your question.

Categories