i want to insert my table in sql server from php. but i don't understand how to fix it form my query. is there any suggest that can help my query. is that correct that case statement can be put into php code like i did?
this is my code :
<?
include "new.php";
$ID_Person = $_POST['IDPerson'];
$Number_Phone_Person = $_POST['NumberPhonePerson'];
$Piority_Phone_Person = $_POST['PiorityPhonePerson'];
$response = array();
if (isset($ID_Person) &&
isset($Number_Phone_Person) &&
isset($Piority_Phone_Person)
)
{
$query = "INSERT INTO T_Person_Phone
(
ID_Person,
Number_Phone_Person,
Piority_Phone_Person
)
VALUES
(
'$ID_Person',
'$Number_Phone_Person',
'$Piority_Phone_Person
CASE When PiorityPhonePerson = 1 Then 'Default'
ELSE 'Priority' + CONVERT (Varchar(5),Piority_Phone_Person) END');";
$hasil = sqlsrv_query($conn,$query,$response);
if($hasil)
{
$response["success"] = 1;
$response["message"] = "User successfully created.";
} else
{
$response["success"] = 0;
$response["message"] = "Eksekusi error.";
die( print_r( sqlsrv_errors(), true));
}
} else
{
$response["success"] = 0;
$response["message"] = "Data gagal disimpan.";
}
// echoing JSON response
echo json_encode($response);
?>
i try any any suggest from google but can help me a lot.
$sql = "INSERT INTO T_Person_Phone
(ID_Person, Number_Phone_Person, Piority_Phone_Person)
VALUES ( '$ID_Person','$Number_Phone_Person','$emailid','$team_name' )";
Your MySql Query is not proper, there is a syntactical mistake.
You can run this query directly to phpMyAdmin or Sql prompt, you will get error.
beacoze you have missed single quotes here
'$Piority_Phone_Person
CASE When PiorityPhonePerson = 1 Then 'Default'
ELSE 'Priority' + CONVERT (Varchar(5),Piority_Phone_Person) END'
you can try below one and customise it according to your requirements.
INSERT INTO T_Person_Phone
(
ID_Person,
Number_Phone_Person,
Piority_Phone_Person
)
VALUES
(
'$ID_Person',
'$Number_Phone_Person',
'$Piority_Phone_Person
CASE When PiorityPhonePerson = 1 Then `Default`
ELSE `Priority` + CONVERT (Varchar(5),Piority_Phone_Person) END');";
Related
I have a database in which there are NOT NULL and NULL fields (the NULLs are of the VARCHAR type).
When I try to enter data in the NULL fields via my query, it does not insert them.
The data isn't entered all at the same time:
with a form I insert the data in the NOT NULL fields
with another form insert the data in the NULL fields.
Why doesn't the query for entering data in the NULL fields sork?
I tried to find an answer to similar questions, but they don't work or are not suitable for my problem:
MySQL Insert Select - NOT NULL fields
Insert NULL into DATE field MySQL 5.6
FIRST FORM register.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
// echo $_SERVER["DOCUMENT_ROOT"]; // /home1/demonuts/public_html
//including the database connection file
include_once("config.php");
$id_akR = $_POST['id_akR'];
$numero_telefonoR = $_POST['numero_telefonoR'];
if($id_akR == '' || $numero_telefonoR == '' ){
echo json_encode(array( "status" => "false","message" => "Parameter missing!") );
}else{
$query= "SELECT * FROM RistoratoreAK WHERE id_akR='$id_akR' OR numero_telefonoR ='$numero_telefonoR' ";
$result= mysqli_query($con, $query);
$query2 = "SELECT ak_id, numero_telefono FROM AccountKit WHERE ak_id = '$id_akR' OR numero_telefono = '$numero_telefonoR'";
$result2= mysqli_query($con, $query2);
if(mysqli_num_rows($result) > 0){
echo json_encode(array( "status" => "false","message" => "User already exist in Ristoratore!") );
}else if(mysqli_num_rows($result2) > 0) {
echo json_encode(array( "status" => "false","message" => "User already exist in Cliente!") );
}else{
$query = "INSERT INTO RistoratoreAK (id_akR, numero_telefonoR) VALUES ('$id_akR','$numero_telefonoR')";
if(mysqli_query($con,$query)){
$query= "SELECT * FROM RistoratoreAK WHERE numero_telefonoR ='$numero_telefonoR'";
$result= mysqli_query($con, $query);
$emparray = array();
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
}
echo json_encode(array( "status" => "true","message" => "Successfully registered!" , "data" => $emparray) );
}else{
echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
}
}
mysqli_close($con);
}
} else{
echo json_encode(array( "status" => "false","message" => "Error occured, please try again!") );
}
?>
SECOND FORM register2.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'config2R.php';
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
$nome = $_POST['nomeR'];
$cognome = $_POST['cognomeR'];
$data_nascita = $_POST['data_nascitaR'];
$sesso = $_POST['sessoR'];
$nome_ristorante = $_POST['nome_ristoranteR'];
$CheckSQL = "SELECT nome_ristorante FROM RistoratoreAK WHERE nome_ristorante='$nome_ristorante'";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)){
echo 'Ristorante già registrato';
}
else{
$Sql_Query = "INSERT INTO RistoratoreAK (nomeR,cognomeR,data_nascitaR,sessoR,nome_ristorante) values ('$nome','$cognome','$data_nascita','$sesso','$nome_ristorante')";
if(mysqli_query($con,$Sql_Query))
{
echo 'Registration Successfully';
}
else
{
echo 'Something went wrong';
}
}
}
mysqli_close($con);
?>
My DB contains a table called "RistoratoreAK", the fields are :
id INT PrimaryKey
id_ak VARCHAR NOT NULL
number VARCHAR NOT NULL
nomeR VARCHAR NULL
cognomeR VARCHAR NULL
sessoR VARCHAR NULL
data_nascitaR VARCHAR NULL
nome_ristorante VARCHAR NULL
note: Excuse me if the code isn't secure (I didn't use PDO), this code is just a test to learn how to upload data to the database.
After the first form, you INSERT a new entry into your table with the id and id_ak. This is fine, and it works.
But after the second form, you should not INSERT another entry, but UPDATE an existing one instead (the one that you created before).
To update it, you need to know the id of the existing entry.
Having that, you can make an UPDATE query like this:
UPDATE
RistoratoreAK
SET
nomeR = '$nome',
cognomeR = '$cognome',
data_nascitaR = '$data_nascita',
sessoR = '$sesso',
nome_ristorante = '$nome_ristorante'
WHERE
id = $existing_id
I have coded a php script that will generate a pdf file from some results. My select statement needs to be filtered with a where condition. Basically, I want to test my php script to see if it works well or not. How can I assign the where condition in the link itself?
this is my php code :
$query = "
SELECT
user_id
FROM TahdirUsers
WHERE
username = ':username'
";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row)
{
if ($_POST['password'] === $row['password'])
{
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
}
else
{
$response["success"] = 0;
$response["message"] = "Invalid password!";
$pdf = new PDF(PDF_PAGE_ORIENTATION,PDF_UNIT,PDF_PAGE_FORMAT,true, 'UTF-8', true);
$pdf->SetFont('aefurat', '', 12, '', true);
// The first Parameter is localhost again unless you are retrieving data from a different server.
// The second parameter is your MySQL User ID.
// The third parameter is your password for MySQL. In many cases these would be the same as your OS ID and Password.
// The fourth parameter is the Database you'd like to run the report on.
$pdf->connect('xxxxxxxxx','xxxxxxx','xxxxxxxxx','xxxxxxxx');
// This is the title of the Report generated.
$attr=array('titleFontSize'=>24,'titleText'=>'THIS IS MY PDF FILE');
// This is your query. It should be a 'SELECT' query.
// Reports are run over 'SELECT' querires generally.
$pdf->mysql_report($query,false,$attr);
$pdf->Output('htmlout.pdf', 'I');
die(json_encode($response));
}
}
else
{
$response["success"] = 0;
$response["message"] = "this username in not in our database!";
die(json_encode($response));
}
To clarify my question. If my website link is www.testtesttest.com, how do I implement the where condition from the select statement in the URL
If my comment above is wrong, and your question is literally "how do I pass data from a URL to a PHP script", the answer is that you use the $_GET superglobal variable to access query strings in the standard format .../path/to/script.php?var1=value1&var2=value2...
So the URL http://amjad-test.site40.net/arabictest.php?username=imsop will execute 'arabictest.php' and populate the variable $_GET['username'] with the value 'imsop'. You then use that variable wherever you like in your code.
I'm trying to implement a way to keep names, entered in an android app and sent to a server, from being used again. I figured the easiest way to do this is create another table and every time a product is added the name is added to the name table. I'm very new to php so this may seem like a very simple question but how would I go about checking the table to see if name is already on it.
here is what I go so far(most of it was already there just the commented out is my thought process)
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['longitude']) && isset($_POST['latitude']) && isset($_POST['pavement']) && isset($_POST['traffic']) && isset($_POST['environment'])) {
//if(Name is not already in list of names){
$name = $_POST['name'];
$longitude = $_POST['longitude'];
$latitude = $_POST['latitude'];
$pavement = $_POST['pavement'];
$traffic = $_POST['traffic'];
$environment = $_POST['environment'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO spots(name, longitude, latitude, pavement, traffic, environment) VALUES('$name', '$longitude', '$latitude', '$pavement', '$traffic', '$environment')");
//add new name to table
//$result2 = mysql_query("INSERT INTO names(name) VALUES('$name')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Spot successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
/*
} else {
// name already taken
$response["success"] = 0;
$response["message"] = "Name has already been taken.";
// echoing JSON response
echo json_encode($response);
}
*/
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Sorry for the simple question but thank you in advance,
Tyler
You could do a SELECT query like this:
$query = mysql_query("SELECT * FROM spots WHERE name='$name'");
$count = mysql_num_rows($query);
if($count == 0){
// name not in database
}
else{
// name is in database
}
However, this is using mysql_ functions which are deprecated. Please use mysqli_ functions instead.
Make name primary key in names table or apply unique constrain and check for duplicate key error after insertion in names table
Or you can first query table to see if name is already there or not
$result3 = mysql_query("SELECT * FROM names WHERE name='$name'");
if(mysql_num_rows($result3) <= 0 )
{
// name is not in names table
// now insert in names table
}
i have table with 2 primary key and 1 foreign key. the problem is when i want to insert data to table, but something error just happen.
this is my mysql relation table
datatype PiorityPhonePerson is tinyint and CodePhonePerson is nchar.
and this is my php data :
<?
include "new.php";
$ID_Person = $_POST['IDPerson'];
$Number_Phone_Person = $_POST['NumberPhonePerson'];
$Piority_Phone_Person = $_POST['PiorityPhonePerson'];
$Code_Phone_Person = $_POST['CodePhonePerson'];
$response = array();
if (isset($ID_Person) &&
isset($Number_Phone_Person) &&
isset($Piority_Phone_Person) &&
isset($Code_Phone_Person)
)
{
$query = "INSERT INTO T_Person_Phone
(
ID_Person,
Number_Phone_Person,
Piority_Phone_Person,
Code_Phone_Person
)
VALUES
(
(SELECT ID_Person FROM T_Person
where ID_Person = '$ID_Person'),
'$Number_Phone_Person',
'$Piority_Phone_Person',
'$Code_Phone_Person'
)
";
$hasil = sqlsrv_query($conn,$query,$response);
if($hasil)
{
$response["success"] = 1;
$response["message"] = "User successfully created.";
} else
{
$response["success"] = 0;
$response["message"] = "Eksekusi error.";
die( print_r( sqlsrv_errors(), true));
}
} else
{
$response["success"] = 0;
$response["message"] = "failed to save.";
}
// echoing JSON response
echo json_encode($response);
?>
when i try to execute,it can't be insert into my table.
please help me.
What exactly is the error?
Without knowing the exact error we would just be stabbing the problem in the dark. Could you please stick these two lines at the top of your PHP page?
error_reporting(E_ALL);
ini_set('display_errors', '1');
Let us know what's the error is and then we can suggest :)
Looking at your query in the INSERT it doesn't make sense to do that if you are selecting the value you are giving to the query:
$query = "INSERT INTO T_Person_Phone (
ID_Person,
Number_Phone_Person,
Piority_Phone_Person,
Code_Phone_Person
)
VALUES(
'$ID_Person',
'$Number_Phone_Person',
'$Piority_Phone_Person',
'$Code_Phone_Person')"
I have two arrays $fuel and $hours, with same number of data and i want to insert them in the same time in a database.
here is what i have:
$fuellength = count($fuel);
$f = 0;
for($f=0;$f<$fuellength;$f++){
if ($fuel[$f] > 0){
if (
mysql_query("INSERT INTO grafiku (vehicle_plate, fuel_level, date_hour) VALUES (".$userid.", ".$hours[$f].", '".$fuel[$f]."')");
)
echo "data has been inserted";
else
echo "data has not been inserted";
} //end if
}//end for
It shows me nothing! Is it correct to use 'for' loop for arrays? Or should i use only 'foreach'? If so, how can i loop throw both arrays in the same time??
Thanks in advance!
Best regards
If your code is exactly like this you won't see anything because you have a fatal php error.
You have an ELSE statement whithout a starting IF statement.
Remove the comments from your IF statement and it should be working again.
$fuellength = count($fuel);
$f = 0;
for($f=0;$f<$fuellength;$f++){
if ($fuel[$f] > 0){
$qryStr = "INSERT INTO grafiku (vehicle_plate, fuel_level, date_hour) VALUES (".$userid.", ".$hours[$f].", '".$fuel[$f]."')";
echo $qryStr."/br";
}
}
Check whether you are getting the query and the values.
There is an error in your code,
Parse error: syntax error, unexpected T_ELSE in < file name > on line 12
<?php
$fuellength = count($fuel);
$f = 0;
for($f=0;$f<$fuellength;$f++){
if ($fuel[$f] > 0){
if (mysql_query("INSERT INTO grafiku (vehicle_plate, fuel_level, date_hour) VALUES (".$userid.", ".$hours[$f].", '".$fuel[$f]."')"))
echo "data has been inserted";
else
echo "data has not been inserted";
} //end if
}//end for
?>
Assuming that you have established a connection with your MySQL Server:
$cn = mysql_connect("hostname", "username", "password");
Assuming that you have selected your database:
mysql_select_db("databasename", $cn);
Your logic is correct. But your SQL insert order is not matching your fields. You are trying to insert $fuel[$f] data into date_hour field.
$f = 0;
$added = 0;
$noAdded = 0;
while($f < count($fuel))
{
if ($fuel[$f] > 0)
{
if(mysql_query("INSERT INTO grafiku
(vehicle_plate, fuel_level, date_hour)
VALUES (".$userid.", ".$fuel[$f].", '".$hours[$f]."')"
))
$added++;
else
$noAdded++;
}
$f++;
}
//Then you can display additional information after inserting is done.
echo $added . " data has been added to table.";
echo "<br />";
echo $noAdded . " data could not be added to table.";