I am trying to insert data in table in mysql database through php code but I am always getting following error:
Invalid query: Table 'whatsup_wp1.pushDevices' doesn't exist
I am using following code:
<?php
$deviceid = $_GET["deviceid"];
$link = mysql_connect('localhost', 'whatsup_wp1', 'XSvUCl0FugzV4');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('whatsup_wp1', $link);
if (!$db_selected) {
echo 'Can\'t use whatsup_wp1 : ' . mysql_error();
}
else
{
//echo 'connect';
}
//$query = "select count(*) from city";
//$query = "insert into devices (pushID) values('".$deviceid."')";
$query = "INSERT INTO pushDevices(device) VALUES ('".$deviceid."')";
echo $query;
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
echo $result;
?>
This database have more tables and I am able to use them. I am having problem with the tables that I am creating today. They appears in phpmyadmin but somehow I am not able to get use them through my php code.
Any help may be vital for me. I have spent complete day on it.
Thanks
Pankaj
Its hard to tell by What your saying but i have a suggestion.... It looks like theres no table selected try this
it formatted like this
$query = "INSERT INTO mydb.mytable
(mytablefield)
VALUES
('myfieldvalue')"
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
My guess is you meant for it to be like this?
$query = "INSERT INTO whatsup_wp1.devices
(device)
VALUES
('".$deviceid."')"
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
And for security reasons i recommend this...
else
{
//echo 'connect';
$deviceid = mysql_real_escape_string(stripslashes($deviceid));
}
Change to
else
{
//echo 'connect';
$deviceid = mysql_real_escape_string(stripslashes($deviceid));
}
Personally i just use it like this
$result = mysql_query("INSERT INTO mytable
(mytablefield)
VALUES
('myfieldvalue')");
if($result){echo "Works!";}
else{die('Invalid query: ' . mysql_error());exit();}
If you are on Linux, check that the case is the same.
On windows MySql is case insensitive, on Linux, it is case sensitive.
Also, you are missing a space after pushDevice: pushDevice(...
Related
what is wrong with this script? it keeps giving my erros but will not tell me what is wrong
I need this to lookup channel number from the item number passed in url. then echo the channel number
<?php
$id = $_GET['item'];
if (!$link = mysql_connect('server', 'user', 'pass')) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db('xmlrpc', $link)) {
echo 'Could not select database';
exit;
}
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'")or die(mysql_error());
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['channel'];
}
mysql_free_result($result);
?>
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'") or die(mysql_error());
To
$sql = "SELECT channel FROM channels WHERE item = '".$_GET['item']."'";
As a sidenote do not use mysql_ functions, they became obsolete (PHP 5.5). Use PDO instead for example, as it stands your code is vulnerable to SQL injections.
when item is already declared as a variable $id
$id = $_GET['item'];
you could already use it as a variable in your mysql
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'")or die(mysql_error());
change it into
$sql="SELECT * FROM channels WHERE item ='$id'";
The below script works fine but only for the first record in the array.
$codes = array(1,2,3,4,5,6,7,8,9,10); // demo for this question, i actually have 1000+
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect1: ' . mysql_error());
}
$con2 = mysql_select_db("db", $con);
if (!$con2)
{
die('Could not connect2: ' . mysql_error());
}
$productsid = "select `products_id` from `coupons_products` where `coupons_id`=58386264";
$productsquery = mysql_query($productsid);
foreach ($codes as $code) {
while ($productid = mysql_fetch_assoc($productsquery)){
$sql = "insert into discount_coupons_to_products values (
'$code',
'{$productid['products_id']}')";
$con4 = mysql_query($sql);
if (!$con4)
{
die('Could not connect4: ' . mysql_error());
}
}
} // end foreach
I have an array of codes from the database that need apply only to specific products(same as 58386264). The codes works but only for the first coupon in the array ($codes).
If I understand what it means, you will need to run mysql_query command every step inside foreach, not just run mysql_fetch_assoc like you're actually doing.
In my database I have the following schema:
Answers:
answerId(PK) auto_inc
answer
questionId
I am passing the following JSON String to my php file:
[{"answer":"bnk","questionId":"1"},{"answer":"1","questionId":"2"},{"answer":"b n","questionId":"3"},{"answer":"3","questionId":"4"},{"answer":"rgb","questionId":"5"},{"answer":"No","questionId":"6"},{"answer":"0","questionId":"7"},{"answer":"0","questionId":"8"},{"answer":"0","questionId":"9"},{"answer":"0","questionId":"10"},{"answer":"0","questionId":"11"},{"answer":"0","questionId":"12"},{"answer":"0","questionId":"13"},{"answer":"0","questionId":"14"},{"answer":"3","questionId":"18"},{"answer":"nko","questionId":"19"},{"answer":"hhkl","questionId":"15"},{"answer":"2","questionId":"16"},{"answer":"vnlf hugg","questionId":"17"}]
This is captured via a post request in $_POST['answers']:
if(isset($_POST['submitanswer'])){
$dbh = connect();
$user = $_POST['user'];
$entry = $_POST['entryId'];
$answers = $_POST['answers'];
$answers = json_decode($answers); //decode JSON answers
//for loop to iterate through answers ans insert new row into database
}
How do I iterate through the answers array and insert a new row into my answers table?
Something like:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES ($row['answer'], $row['questionId'])";
mysql_query($query);
}
If this code didn't work for you, try this:
foreach($answers as $row){
$query = "INSERT INTO Answers (answer, questionId) VALUES (".$row['answer'].", ".$row['questionId'].")";
mysql_query($query);
}
Otherwise, I can't spot anything wrong here.
I gues you know this but make sure your connection string is good.
Actually this is what I do. Probably a bit much info for you, also I do all that concatenation in the SQL so I can easily comment out fields for testing.
$Link = mysql_connect( $Host , $User , $Password , $DBName);
if (!$Link) {
die('Could not connect: ' . mysql_error());
}
$sql = "insert into table "
."("
."hashfirstName".","
."hashfamilyName".","
."hashemailAddress"
.")"
."values ("
."'$firstNameHashed'".","
."'$familyNameHashed'".","
."'$emailAddressHashed'"
.")";
mysql_select_db($DBName , $Link) or die("Database error in insertdata<br>"."Error #" . mysql_errno() . ": " . mysql_error());
if(!mysql_query($sql , $Link))
{
$errors['sql'] = $sql;
$errors['DBName'] = $DBName;
$errors['Link'] = $Link;
$errors['status'] = "false"; //There was a problem saving the data;
echo json_encode($errors);
}
else
{
$errors['status'] = "true";
echo json_encode($errors);
}; // if(!mysql_query( $DBName , $sql , $Link))
I'm using jqueryui and its Autocomplete plugin. It use a json to extract items.
I want to modify it so that items will be extracted from my db.
Here is how items should be :
$items = array(
"Great <em>Bittern</em>"=>"Botaurus stellaris",
"Great2 <em>Bittern</em>"=>"Botaurus stellaris 2"
);
How to make an sql query that extract data from a table and write it like the code above into the php file ?
Table : customer
id_customer | name_customer | country_customer
I want that array produce id_customer => name_customer
The query is just:
SELECT id_customer, name_customer FROM customer
and you can generate the array like so (assuming you are using MySQL):
$items = array();
$result = mysql_query($sql);
while(($row = mysql_fetch_assoc($result))) {
$items[$row['id_customer']] = $row['name_customer'];
}
References: MySQL SELECT syntax, mysql_query(), mysql_fetch_assoc()
<?php
//Use mysql_connect for connect to a Db
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select a DB
$db_selected = mysql_select_db('db_name', $link);
if (!$db_selected) {
die ('Can\'t use dbame_n : ' . mysql_error());
}
//Build a query
$sql = "SELECT id_customer, name_customer FROM customer";
//Send de query to db
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// Initialize Array
$arr_customers = array();
while(($row = mysql_fetch_assoc($result))) {
$arr_customers[$row['id_customer']] = $row['name_customer'];
}
// convert to JSON
$json = json_encode($arr_customers);
// Send to JqueryUI
echo $json;
exit();
?>
What is wrong with this code? I get an empty array. I am passing a PHP variable to the query, but it doesn’t work; when I give a hardcoded value the query returns a result.
echo $sub1 = $examSubject[$i];
$subType = $examType[$i];
$query = $this->db->query("select dSubject_id from tbl_subject_details where dSubjectCode='$sub1'");
print_r($query->result_array());
Look up “SQL injection”.
I’m not familiar with $this->db->query; what database driver are you using? The syntax for escaping variables varies from driver to driver.
Here is a PDO example:
$preqry = "INSERT INTO mytable (id,name) VALUES (23,?)";
$stmt = $pdo->prepare($preqry);
$stmt->bindparam(1,$name);
$stmt->execute();
failing to see what you database abstraction layer ($this->db) does, here's the adjusted code from example1 from the mysql_fetch_assoc documentation
<?php
// replace as you see fit
$sub1 = 'CS1';
// replace localhost, mysql_user & mysql_password with the proper details
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = 'SELECT `dSubject_id` ';
$sql .= 'FROM `tbl_subject_details` ';
$sql .= "WHERE `dSubjectCode` ='$sub1';";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['dSubject_id'];
}
mysql_free_result($result);
?>
Let me know what the output is, I'm guessing it will say: 6
Is it CodeIgniter framework you're using (from the $this->db->query statement). If so, why don't you try:
$this->db->where('dSubjectCode',$sub1);
$query = $this->db->get('tbl_subject_details');
If this doesn't work, you've got an error earlier in the code and $sub1 isn't what you expect it to be.