I have database contain table named demnads
table contain 11 cell first one is id auto increasement
I want to add data's with this sql command in php :
<?php
$hostname_mystore = "localhost";
$database_mystore = "mystore";
$username_mystore = "root";
$password_mystore = "";
$mystore = mysql_pconnect($hostname_mystore, $username_mystore, $password_mystore) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_query("set character_set_server='utf8'");
mysql_query("set names 'utf8'");
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql= "INSERT into demands ( itemname , case , cname , fatora , client , cdate , ctime , prices , cmobile , numbers) values('$item[$i]','$cases[$i]','$customer[$i]','$fatora[$i]','$client[$i]','$dates[$i]','$times[$i]','$price[$i]','$mobile[$i]','$numbers[$i]' )";
?>
but data's didn't be inserted
You have switched from the mysql library (which is deprecated) to mysqli:
mysqli_connect_errno()
You should use one or the other.
Also, embedded array values need to be enclosed in curly brackets{$item[$i]}.
This assumes, of course, that these arrays and $i are defined elsewhere.
And you haven't shown the statement that actually inserts the data.
You forgot to call mysql_query( $sql, $conn )
Enclose your column names with backticks. case is a keyword within MySQL and as such can not be used as a column name without the backticks!
$sql= "INSERT into demands ( `itemname` , `case` , `cname` , `fatora` , `client` , `cdate` , `ctime` , `prices` , `cmobile` , `numbers`) values('$item[$i]','$cases[$i]','$customer[$i]','$fatora[$i]','$client[$i]','$dates[$i]','$times[$i]','$price[$i]','$mobile[$i]','$numbers[$i]' )";
You said your table name is demnads . But in Coding you used demands?
Check again.
Related
I have a Table named "status" Which is used to store objects status. The table has 5 columns and except "symbol" column which it's type is VARCHAR utf8mb4_unicode_ci, All the others are just typical integers.
The problem is that because the symbol column can store English and Non-English characters, It returns NULL(With var_dump($row)) When I use my php file "getStatus.php" to retrieve the data from a row with Non-English symbol but It works well when I use English characters as symbol.
This is my table(the symbol on the second row is "تست"):
This is the php code, "getStatus.php" :
if(!isset($_GET["symbol"]))
die("please specify the symbol");
$con = mysqli_connect("localhost","root","******","****");
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "SELECT * FROM `status` WHERE `symbol` = '" . $_GET["symbol"] . "';";
$result = mysqli_query($con,$query);
if (!$result)
die("unable to retreive status");
$row = mysqli_fetch_assoc($result);
if ($row["status"] == 1)
echo $row["percentage"];
else
echo -1;
I can successfully get data When I execute getStatus.php?symbol=EU which calls mysql with
SELECT * FROM `status` WHERE `symbol` = 'ER';
But When I execute getStatus.php?symbol=تست, I got null! The confusing point is that if I copy the query and enter it in mysql command line It will work but it doesn't work when I send the same query with mysqli in php!!
SELECT * FROM `status` WHERE `symbol` = 'تست';
Why it works in mysql commandline and phpmyadmin but not with mysqli?
I'm getting an error 'undeclared variable: temp' when I run this...
<?php
$maketemp = "CREATE TEMPORARY TABLE temp(`itineraryId` int NOT NULL, `live` varchar(1), `shipCode` varchar(10), `description` text, `duration` varchar(10), PRIMARY KEY(itineraryId))";
mysql_query( $maketemp, $connection ) or die ( "Sql error : " . mysql_error ( ) );
$inserttemp = "SELECT live, id AS itineraryId, ship AS shipCode, description AS description, duration AS length FROM cruises WHERE live ='Y' INTO temp";
mysql_query( $inserttemp, $connection ) or die ( "Sql error : " . mysql_error ( ) );
$select = "SELECT intineraryId, shipCode, description, duration FROM temp";
$export = mysql_query ( $select, $connection ) or die ( "Sql error : " . mysql_error( ) );
Any ideas ?
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
This code should work:
<?php
$maketemp = "
CREATE TEMPORARY TABLE temp_table_1 (
`itineraryId` int NOT NULL,
`live` varchar(1),
`shipCode` varchar(10),
`description` text,
`duration` varchar(10),
PRIMARY KEY(itineraryId)
)
";
mysql_query($maketemp, $connection) or die ("Sql error : ".mysql_error());
$inserttemp = "
INSERT INTO temp_table_1
(`itineraryId`, `live`, `shipCode`, `description`, `duration`)
SELECT `id`, `live`, `ship`, `description`, `duration`
FROM `cruises`
WHERE `live` = 'Y'
";
mysql_query($inserttemp, $connection) or die ("Sql error : ".mysql_error());
$select = "
SELECT `itineraryId`, `shipCode`, `description`, `duration`
FROM temp_table_1
";
$export = mysql_query($select, $connection) or die ("Sql error : ".mysql_error());
I guess you are going to do more stuff with the temporary table, or are just playing with it, but if not be aware that the whole code could be summed up with:
<?php
$query = "
SELECT `id` AS 'itineraryId', `ship`, `description`, `duration`
FROM `cruises`
WHERE `live` = 'Y'
";
$export = mysql_query($query, $connection) or die ("Sql error : ".mysql_error());
I like to use heredoc to help me construct embedded sql query (just to help make any subtle error glaring); so your first query would look something like this:
$maketemp =<<<s
CREATE TEMPORARY TABLE temp(
`itineraryId` int NOT NULL,
`live` varchar(1),
`shipCode` varchar(10),
`description` text,
`duration` varchar(10),
PRIMARY KEY(itineraryId));
s;
Then if you want to correct the 2nd query without listing the fields of the table you want to insert the records, you have to list the fields in the same order.
Just the query this time:
INSERT INTO temp
SELECT id, live, ship, description, duration
FROM cruises
WHERE live = 'y';
And last thing about temporary variable is this: Check out the part about its visibility.
You can use the TEMPORARY keyword when creating a table. A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed.
http://dev.mysql.com/doc/refman/5.5/en/create-table.html
What that means is this: when you're connected to MySQL directly, e.g. through a command line interface like this:
mysql> #our query here line-by-line
Then you're essentially on the same connection through all of your multiple queries as long as your session is active.
But in an external script (like PHP, for example), just because it's on the same script file doesn't necessarily mean it's the same connection so that by the time you execute your insert query, your temp table is not visible to that connection session.
Try to concat all the queries, send it all within a single command/query execution.
Good luck.
The second query is not correct.
From the reference -
MySQL Server doesn't support the SELECT ... INTO TABLE Sybase SQL
extension. Instead, MySQL Server supports the INSERT INTO ... SELECT.
standard SQL syntax, which is basically the same thing.
Try this one instead -
INSERT INTO temp
SELECT live
, id AS itineraryId
, ship AS shipCode
, description AS description
, duration AS length
FROM
cruises
WHERE
live = 'Y'
Suppose I have a table called "device" as below:
device_id(field)
123asf15fas
456g4fd45ww
7861fassd45
I would like to use the code below to insert new record:
...
$q = "INSERT INTO $database.$table `device_id` VALUES $device_id";
$result = mysql_query($q);
...
I don't want to insert a record that is already exist in the DB table, so how can I check whether it have duplicated record before inserting new record?
Should I revise the MYSQL statement or PHP code?
Thanks
UPDATE
<?php
// YOUR MYSQL DATABASE CONNECTION
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'device';
$table = 'device_id';
$db_link = mysql_connect($hostname, $username, $password);
mysql_select_db( $database ) or die('ConnectToMySQL: Could not select database: ' . $database );
//$result = ini_set ( 'mysql.connect_timeout' , '60' );
$device_id = $_GET["device_id"];
$q = "REPLACE INTO $database.$table (`device_id`) VALUES ($device_id)";
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
Since I understood well your question you have two ways to go, it depends how you would like to do the task.
First way -> A simple query can returns a boolean result in the device_id (Exists or not) from your database table. If yes then do not INSERT or REPLACE (if you wish).
Second Way -> You can edit the structure of your table and certify that the field device_id is a UNIQUE field.
[EDITED]
Explaining the First Way
Query your table as follow:
SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'
then if you got results, then you have already that data stored in your table, then the results is 1 otherwise it is 0
In raw php it looks like:
$result = mysql_query("SELECT * FROM `your_table` WHERE `device_id`='123asf15fas'");
if (!$result)
{
// your code INSERT
$result = mysql_query("INSERT INTO $database.$table `device_id` VALUES $device_id");
}
Explaining the Second Way
If your table is not yet populated you can create an index for your table, for example go to your SQL command line or DBMS and do the follow command to your table:
ALTER TABLE `your_table` ADD UNIQUE (`device_id`)
Warning: If it is already populated and there are some equal data on that field, then the index will not be created.
With the index, when someone try to insert the same ID, will get with an error message, something like this:
#1062 - Duplicate entry '1' for key 'PRIMARY'
The best practice is to use as few SQL queries as possible. You can try:
REPLACE INTO $database.$table SET device_id = $device_id;
Source
I am using XMAPP and MySQL is running as it should. In phpMyAdmin, I don't really get the point so I tried creating one in PHP. With this code it tells me the database benutzer. benutzer doesn't exists although I created one in phpMyAdmin and in this code:
<?php
$connect = mysql_connect("127.0.0.1","root","") or die ("Alles scheisse!");
$db = mysql_select_db("benutzer") or die ("Keine benutzer!");
$sql = "CREATE TABLE 'benutzer'
id VARCHAR(100),
name VARCHAR(100),
mail VARCHAR(100),
points INT(1000)
)";
$sql = "INSERT INTO benutzer(`id` , `name` , `mail` , `points`)VALUES(NULL , 'Liam', 'liam#mail.com', '100');";
$db_erg = mysql_query($sql)
or die("Anfrage fehlgeschlagen: " . mysql_error());
?>
Have you also created a table "benutzer" inside db "benutzer"? Your code does not execute your first SQL statement "CREATE TABLE.." so there will be no table "benutzer" if you don't have one created in phpmyadmin.
Did you created the database under the root user? Because you are connecting to the root in your code.
Okay, I have searched for an error in this code for days and haven't succeeded. This is supposed to insert a new user (new row) into a table. For some reason, it does absolutely nothing to the mysql table "users." I can connect and retrieve data from the table perfectly fine. Please help!
include('config.php');
$db = mysql_connect('localhost', $user, $pass);
if(!$db)
{
echo 'Cannot find the database';
exit;
}
$dbname = $user;
mysql_select_db($dbname) or die('Cannot select the database');
(other code that I have not posted because I have tested it without this code and it produces the same result)
$query = "INSERT INTO users VALUES (
NULL,
'$Passw' ,
'$Fname' ,
'$Lname' ,
'$Email' ,
'$Add1' ,
'$Add2' ,
'$City' ,
'$State' ,
'$Zip ,
'$Country' ,
'$Phone' ,
'$Bio')";
$result = mysql_query($query);
1 : Retrieve the possible MySQL error using:
if ($result === false)
echo mysql_error();
2 : It's a good practice to specify the table fields when you use INSERT
INSERT INTO table (field1, field2, field3) VALUES ('value1', 'value2', 'value3');
Because if you don't, and your DB structure changes, you will have to update the VALUES(...) part.
3 : use mysql_real_escape_string() when inserting strings in queries for MySQL, to avoid SQL injection problems.