I'm still getting mysql error in my PHP script.
Problematic code:
$mquery = mysql_query("SELECT m.`id`, m.`name`, NULL AS `type`, NULL AS `code`, 0 AS `cat` FROM `menu` m UNION ALL SELECT l.`id`, l.`name`, l.`type`, l.`code`, l.`cat` FROM `lines` l UNION ALL SELECT s.`id`, s.`name`, s.`site`, s.`site`, s.`cat` FROM `sites` s ORDER BY `name` ASC");
if(!$mquery) { echo mysql_error(); die(); }
while($mdata = mysql_fetch_assoc($mquery)) { ... }
When i put this query into PhpMyAdmin - all is OK, i will get result. When I put this query into MySQL Workbench - all is OK, i will get result.
AND NOW: When I run script with parameter (http://domain/index.php?site=ABC) - ALL IS OK. When I run script without parameter (http://domain/index.php) - I get mysql error on this query: "Table 'test.menu' doesn't exist".
What "test.menu"?! Where is "test"? I don't want any "test", I have no "test" in my query. And why is it related on parameter in url? It's not dynamically generated query. Where is problem?
Sorry for my english
Solved, script structure:
$mydb = mysql_connect(...);
mysql_select_db(..., $mydb);
mysql_set_charset('utf8', $mydb);
function newMenu($db)
{
$mquery = mysql_query("...", $db);
if(!$mquery) { echo mysql_error(); die(); }
while($mdata = mysql_fetch_assoc($mquery) { ... }
}
myMenu($mydb);
But what i don't understand is: Why is it working without "$db" when parameter 'site' is in url?
Please check your mysql configuration in PHP. I am pretty sure you are using database name as 'test' because you've copied the code from somewhere. Change it to the actual name of your database and it will work.
The second parameter of mysql_query must be a connection variable.
<?php
$con = mysql_connect("localhost", "root", "mypass") or
die("Could not connect: " . mysql_error());
mysql_select_db("tutorials");
$result = mysql_query("select * from tutorials");
echo "<h2>Here is a list of the topics:</h2>";
while ($row = mysql_fetch_array($result)) {
echo $row['name']."<br />";
}
mysql_close($con);
?>
Could you give full php script? is the database config related to 'site' parameter ?
Related
I am new to PHP and I have taken up an online tutorial, till now I had been working fine but now my database is not returning the query, though when I go to PHPmyadmin there I can get the query working fine.
Following is the code
<?php
ob_start();
//Delete Item question to admin and delete product
include"../storescripts/connect_to_mysql.php";
if (isset($_GET['deleteid'])) {
echo 'Do you really want to delete the item with ID '.$_GET['deleteid'].'?Yes|No';
exit();
}
if(isset($_GET['yesdelete'])){
// Delete the actual product and delete picture also
//delete from database
//$id_to_delete = $_GET['yesdelete'];
//echo $id_to_delete;
$sql =mysqli_query( "DELETE * FROM `products` WHERE `id`=2 LIMIT1 ");
//mysql_query("DELETE * FROM `products` WHERE `id`='$id_to_delete'LIMIT1") or (mysql_error());
//mysqli_query("DELETE * FROM products WHERE id=`$id_to_delete`LIMIT1");// or (mysql_error());
//Unlink file from server
$pictodelete=("../inventory_images/$id_to_delete");
//echo $pictodelete;
if(file_exists($pictodelete)){
unlink($pictodelete);
}
header("location:inventory_list.php");
exit();
}
?>
I would really appreciate the help, my server reads PHP Extension :mysqli .
i dont know what is inside connect_to_mysql.php but at first there is a procedure to connect to a database which i am assuming that you have done correctly, it consist of code which looks something like that at default settings
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename="abc";
// Create connection
$conn = mysqli_connect($servername, $username, $password,$databasename);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
the second things i see in your code
$sql =mysqli_query( "DELETE * FROM `products` WHERE `id`=2 LIMIT1 ");
it contains syntax errors,it should be
$sql =mysqli_query( $conn,"DELETE FROM `products` WHERE `id`=2 LIMIT 1 ");
A space after Limit.
You have not specified the connection in mysqli_query() function.
eg:
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_close($con);
?>
In your case
$sql =mysqli_query( $connectionname,"DELETE * FROM `products` WHERE `id`=2 LIMIT 1 ");
Error at query : $sql =mysqli_query( "DELETE * FROM products WHERE id=2 LIMIT1 ");
replace DELETE * FROM products with DELETE FROM products.DELETE delete row from table.
Procedure like mysqli_query takes at least two argument
Link identifier returned form mysqli_connect
Query string
And you haven't specified link as first arguments you should use returned link in to mysqi_query.
$con = mysqli_connect('localhost','root','password','db');
$sql =mysqli_query( $con,"DELETE FROM `products` WHERE `id`=2 LIMIT1 ");
This link helps you link mysqli_query
I am trying to test if this query runs or not.But i am output with blank screen i.e no output. I am using xampp server.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_pass='';
$mysql_db='a_database';
$con_error='connection error';
$query="SELECT `name` FROM `users` WHERE `id`='1' "; //selecting name from databas where id is 1
$query_run=mysql_query($query); //this is my query
if($query_run)
{
echo 'success';
}
?>
Please help me with this. $query_run neither returns false here nor true. I am not able to understand where the problem is.
First of all try to avoid mysql_* functions from php > 5.4, use mysqli_* function like this.
connect to Databse before running a query like this
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$query="SELECT `name` FROM `users` WHERE `id`='1' "; //selecting name from databas where id is 1
$query_run=mysqli_query($con,$query);
For php < 5.5 use this
$con=mysql_connect("localhost","my_user","my_password","my_db");
$query="SELECT `name` FROM `users` WHERE `id`='1' "; //selecting name from databas where id is 1
$query_run=mysql_query($con,$query);
First of all stop using mysql it is deprecated. Use mysqli now.
In your script you missed the connection to database. Add before your query:
$link = mysqli_connect($mysql_host,mysql_user,$mysql_pass,$mysql_db) or die("Error " . mysqli_error($link));
For more details see this link.
try this:::
<?php
$link = mysqli_connect("localhost","root","root","a_database") or die("Error " . mysqli_error($link));
$query = "SELECT name FROM users" or die("Error in the consult.." . mysqli_error($link));
$result = $link->query($query);
while($row = mysqli_fecth_array($result)) {
echo $row["name"] . "<br>";
}
?>
as mentioned there, use mysqli_*
I need to retrieve the auto increment field from my database table. I tried the following but $id is always just empty.
The insert works too.
My table is as follows:
idint(9) NOT NULL auto_increment,
and id is set as primary
What am I doing wrong?
$conn = mysql_connect($host,$username,$password);
mysql_select_db($database, $conn) or die( "Unable to select database");
include "update_activity.php";
updateActivity("logged in", "On Break");
$date = date("m/d/y"); $starttime = time();
$sesh = $_SESSION['fname']." ".$_SESSION['lname'];
$q = "INSERT INTO `breaks` (date, starttime, user) VALUES ('".$date."', '".$starttime."', '".$sesh."')";
$query = mysql_query($q, $conn);
$id = mysql_insert_id($conn);
echo var_dump($id); exit;
edited to show my more recent attempts
Have read all comments given and your replies to each.
Only one of these is possible:
Either the query works properly OR
You are not getting the generated primary key.
Both of these can never be true.
Define, how you know query is working? Do you know the max PK before and after the running query? Is the insert happening from some other place or thread or even other user? the query is working properly from code or from your mysql client?
To diagnose the problem, we have to go though the normal way.
Dump your generated query before calling mysql_query.
Wrap a error checking system around your query call so php can tell you if the query worked or not. I am sure just by these two steps you will realize the root cause of the problem.
error_reporting(E_ALL);
ini_set('display_errors','on');
echo "before calling: $q\n";
$query = mysql_query($q, $conn);
if(!$query)
{
echo "Error:" . mysql_error($conn);
return;
}
echo " generated id:" . mysql_insert_id($conn);
#adelphia as far as i get the idea there is a problem in the query that is executed.
plz check the query properly
Borrow a lead from this code extracted from here:
http://php.net/manual/en/function.mysql-insert-id.php
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
?>
The problem with your insert query
$q = "INSERT INTO `breaks` (date, starttime, user)
VALUES ('".$date."',
'".$starttime."',
'".$_SESSION['fname'] $_SESSION['lname']."')";
try with this
and main thing you are using most of the deprecated "mysql" things like "mysql_insert_id()"
store the values that u want to pass into an array or variable and pass it in the insert query.
its should work fine then...
I am attempting to match rows in a mysql table using the values from table1.column1 and table2.column3 and then copy the value from table2.column2 into table1.column1 for each match. The query below does what I need to do, but only when I execute it manually (through phpmyadmin). When I try to execute it from PHP I receive the error Unknown column table1.column1 in 'field list'. Here is my PHP code:
<?php
mysql_connect($host,$user,$pass);
$db_selected = mysql_select_db($data);
$sql = "UPDATE table1 t1, table2 t2
SET t1.column1 = t2.column2
WHERE t1.column1 = t2.column3";
$result = mysql_query($sql);
if (!$result) {
echo mysql_error();
} ?>
I know that the mysql connection info works because I am able to execute other queries. From my research on the error it seems that I might need backticks around some part of the query but after several tries I can't figure out the correct way.
EDIT 1 - As requested here is the real query:
UPDATE wp_mf_custom_groups,wp_mf_posttypes
SET wp_mf_custom_groups.post_type=wp_mf_posttypes.type
WHERE wp_mf_custom_groups.post_type=wp_mf_posttypes.id
Outputs the error
Unknown column 'wp_mf_custom_groups.post_type' in 'field list'
Additional information I just realized might be conflicting with it. Before this happens I also renamed the table using:
RENAME TABLE wp_mf_module_groups TO wp_mf_custom_groups
Maybe since the table was just renamed it cant reference it?
Worked when I added backticks to the columns only after WHERE
UPDATE wp_mf_custom_groups,wp_mf_posttypes
SET wp_mf_custom_groups.post_type=wp_mf_posttypes.type
WHERE wp_mf_custom_groups.`post_type=wp_mf_posttypes.id
If query works with PHPmyadmin try this
<?php
$con = mysql_connect($host,$user,$pass) or die('Failed to connect');
$db_selected = mysql_select_db('db_name', $con);
$sql = "UPDATE table1 t1, table2 t2
SET t1.column1 = t2.column2
WHERE t1.column1 = t2.column3";
$result = mysql_query($sql, $con);
if (!$result) {
echo mysql_error();
} ?>
Encountered with the following warning when trying to access the page:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/designand/www/www/random.php on line 13
Everything was working fine when I was testing it on XAMPP.
<?php
$db_hostname = "localhost";
$db_username = "root";
$db_name = "links";
$db_pass = "xxx";
$dbh = mysql_connect ($db_hostname, $db_username, $db_pass) or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db($db_name) or die(mysql_error());
$num_displayed = 1 ;
$result = mysql_query ("SELECT * FROM 'links' ORDER BY RAND() LIMIT $num_displayed");
while($row = mysql_fetch_array( $result ))
{
echo "<img src=\"" . $row["image"] . "\" border=0 alt=\"\">" ;
}
mysql_close($dbh);
?>
An error like that almost always means there's a problem with your query.
To find out what error message MySQL returns, you can put or die(mysql_error()) just before the semicolon after your mysql_query call. You may also want to print the exact query text you send to MySQL, as this may help you to see the actual problem.
Given that I don't know how much you may have anonymized this example, I can't be sure if this is the actual error, but it looks like you've surrounded your table name with apostrophes ('). This is incorrect; the correct character for escaping table and column names is `.
"supplied argument is not a valid MySQL result resource" means that the query didn't return a valid resource. It failed. To view the error just print out mysql_error() after mysql_query().
Could be that the table doesn't exist. Did you check it?
The second thinkg - ORDER BY RAND() is bad! You should think of different ways on how to shuffle the result. Just google it, there are a lot of other ways to do it - ORDER BY RAND() # Google
Try changing this line:
$result = mysql_query ("SELECT * FROM 'links' ORDER BY RAND() LIMIT $num_displayed");
To:
$result = mysql_query ("SELECT * FROM 'links' ORDER BY RAND() LIMIT $num_displayed") or die (echo mysql_error());
It seems like the SQL is failing to return a valid response. Adding the above should show you the last MySQL error and help point you in the correct direction.
Please add this code to get if the mysql is throwing any errors:
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while(....