I want to execute a query that i saved in my database like this:
ID | NAME | QUERY
1 | show_names | "SELECT names.first, names.last FROM names;"
2 | show_5_cities | "SELECT cities.city FROM city WHERE id = 4;"
Is this possible ?
I am kinda noob in php so plz explain if it is possible.
If I understand you correctly, you have your queries saved in the database in a table and you want to execute those.
Break the problem down: you have two tasks to do:
Query the database for the query you want to run.
Execute that query.
It's a bit meta, but meh :)
WARNING: the mysql_ functions in PHP are deprecated and can be dangerous in the wrong hands.
<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
die('Could not connect to mysql');
}
if (!mysql_select_db('mysql_dbname', $link)) {
die('Could not select database');
}
$name = "show_5_cities"; // or get the name from somewhere, e.g. $_GET.
$name = mysql_real_escape_string($name); // sanitize, this is important!
$sql = "SELECT `query` FROM `queries` WHERE `name` = '$name'"; // I should be using parameters here...
$result = mysql_query($sql, $link);
if (!$result) {
die("DB Error, could not query the database\n" . mysql_error(););
}
$query2 = mysql_fetch_array($result);
// Improving the code here is an exercise for the reader.
$result = mysql_query($query2[0]);
?>
if you did create a stored procedure/function you can simply use:
mysql_query("Call procedure_name(#params)")
Thats will work. reference here: http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Querying the table to get the query, then executing that query and looping through the results and outputting the fields
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$RequiredQuery = intval($_REQUEST['RequiredQuery']);
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $sql);
if ($row = mysqli_fetch_assoc($result))
{
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $row['QUERY']);
while ($row2 = mysqli_fetch_assoc($result))
{
foreach($row2 AS $aField=>$aValue)
{
echo "$aField \t $aValue \r\n";
}
}
}
?>
just open the Table and get the individual query in a variable like
$data = mysql_query('SELECT * FROM <the Table that contains your Queries>');
while(($row = mysql_fetch_row($data)) != NULL)
{
$query = $row['Query'];
mysql_query($query); // The Query from the Table will be Executed Individually in a loop
}
if you want to execute a single query from the table, you have to select the query using WHERE Clause.
Related
I am trying to select a row in one table and if it does exists in the second table,do something and if it doesn't,copy the values from table one into the second.
The problem is that,once it finds match (a row that is present in the first and second table),it shows errors for all other rows that did not match.
This is the error
Notice: Trying to get property of non-object in C:\wamp\www\loans.php on line 26
This is my code
<?php
//error_reporting(0);
$mysqli = new mysqli("localhost", "root", "123456", "test");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "select dest_msisdn,text_message,service_id,sender_name from incoming_sms";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$dest_msisdn = $row['dest_msisdn'];
$text_message = $row['text_message'];
$service_id = $row['service_id'];
$sender_name = $row['sender_name'];
/**
Transactions
*/
$m = $mysqli->query("SELECT tel from transactions where tel = $dest_msisdn")->fetch_object()->message;
if(empty($m)){
$ti = "insert into transactions(message,tel) values($text_message,$dest_msisdn)";
$mysqli->query($ti);
}
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
I want to insert rows that i find in table one and are not in table two.
I suggest you check the rows yielded before accessing any properties that the result yields:
$m = $mysqli->query("SELECT tel, message from transactions where tel = $dest_msisdn");
// hi! im missing ^^
// you are accessing the property "message" but its not a selected column in your query
if($m->num_rows <= 0) {
$ti = "insert into transactions(message,tel) values($text_message,$dest_msisdn)";
$mysqli->query($ti);
}
When you chain like that you are assuming there will always be a row. When there isn't a row you cant get the property from it. That's why you get the error. So do something like this:
$r = $mysqli->query("SELECT tel from transactions where tel = $dest_msisdn");
if ($r->num_rows == 0) {
$ti = "insert into transactions(message,tel) values($text_message,$dest_msisdn)";
$mysqli->query($ti);
}
This doesn't answer your question directly, but it will fix your problem and probably solve some others.
The way you are going about inserting (where you first SELECT and then loop through the results in PHP, then SELECT from another table, then INSERT) seems unnecessarily complex. You can get rid of your PHP loop and just execute the INSERT in a single SQL statement without all the PHP overhead. Let your DB do the work for you.
All of this:
$query = "select dest_msisdn,text_message,service_id,sender_name from incoming_sms";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$dest_msisdn = $row['dest_msisdn'];
$text_message = $row['text_message'];
$service_id = $row['service_id'];
$sender_name = $row['sender_name'];
/**
Transactions
*/
$m = $mysqli->query("SELECT tel from transactions where tel = $dest_msisdn")->fetch_object()->message;
if(empty($m)){
$ti = "insert into transactions(message,tel) values($text_message,$dest_msisdn)";
$mysqli->query($ti);
}
}
/* free result set */
$result->free();
Could be changed to just this:
$mysqli->query("INSERT INTO transactions(message,tel) SELECT text_message, tel FROM transactions INNER JOIN incoming_sms on transactions.tel = incoming_sms.dest_msisdn")
sorry to bother you all but I'm really struggling with this one:
I connect to my database fine and then I try the following mysql statements:
$query1 = "select row1 from mydatabase where row2 = $Name ";
$answer1 = mysql_query($query1);
However, a few lines later when I try :
echo $answer1;
I'm given only nulls :(
Can anyone give me any suggestions please?
edit:
SQL logins:
mysql_connect("correct", "username", "password");
mysql_select_db("dbname") or die(mysql_error());
everything you did is right you have just to fetch the data like this:
$query1 = "select row1 from mydatabase where row2 = $Name ";
$answer1 = mysql_query($query1);
while($data= mysql_fetch_array($answer1)){
echo $data['row1'];
}
And this is a complet answer, i adjust it as you need ;)
<?php
//Connect to your database
$con=mysqli_connect("db_hostname","db_user","db_password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Value of the row to select
$row2 = 'some value';
//Make select query
$result = mysqli_query($con, "SELECT row1 FROM MyTable WHERE row2='$row2'");
//Fetch datas
while($row = mysqli_fetch_array($result))
{
echo $row['row1'];
echo "<br>";
}
//Close database
mysqli_close($con);
?>
Good Luck :)
Try using MySQLi_* instead MySQL_* functions and pass the connection variable to the function calls.
If this doesn't work then you might want to try some further debugging by enabling all error reporting and dumping the global scope.
<?php
error_reporting(E_ALL); // Show all errors & warnings
$conn = mysqli_connect("server", "username", "password");
mysqli_select_db($conn, "dbname") or die(mysql_error());
$sql1 = "SELECT `row1` FROM `mydatabase` WHERE `row2` = '".$Name."';";
$query1 = mysqli_query($conn, $sql1);
$answer1 = mysqli_fetch_assoc($query1);
var_dump($GLOBALS); // Dumps all variables in the global scope
?>
add this after $answer1= mysql_query($query1);
while ($row = mysql_fetch_assoc($answer1)) {
// echo data
echo $row['row1'];
}
This is the PHP code for fetching a word that was entered by the user. May I ask on how to show the result of "jhon dewey" if the user entered the keyword "john" on my website as "jhon" only without the last name?
My database fields are:
first_name (contains the first name records)
last_name (contains the last name records)
This is my code. Please help me find the error. Can I change the %john% into a variable so that any word entered by the user can search to my database?
<?php
// Database connection
$sql = new mysqli("localhost", "root", "MYPassword", "test");
if (mysqli_connect_errno ()) {
die(mysqli_connect_error());
exit;
}
$query = "SELECT * FROM `usage` WHERE 'first_name' LIKE %john%";
$result = $sql->query($query);
if (!$result)
die($mysqli->error);
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$result->close();
$sql->close();
print("<pre>");
print_r($rows);
print("</pre>");
?>
Patterns are string literals so they must be wrapped with single quotes.
Second, column names are identifiers so they shouldn't be wrap with single quotes as single quotes are for string literals.
Snippet:
$query = "SELECT * FROM `usage` WHERE `first_name` LIKE '%john%'"
Since your column name is not a reserved keyword, backticks are optional on this case
$query = "SELECT * FROM `usage` WHERE first_name LIKE '%john%'"
Check this one
<?php
// Database connection
$sql = new mysqli("localhost", "root", "MYPassword", "test");
if (mysqli_connect_errno ()) {
die(mysqli_connect_error());
exit;
}
$query = "SELECT * FROM `usage` WHERE `first_name` LIKE '%john%'";
$result = $sql->query($query);
if (!$result)
die($mysqli->error);
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$result->close();
$sql->close();
print("<pre>");
print_r($rows);
print("</pre>");
?>
EDIT: I'm sorry I was unclear, I try to explain it right this time.
I have this data in a database table called tMenu:
id page_nl text
1 index_1 index1_text
2 index_2 index2_text
3 index_3 index3_text
These are 3 pages on my website called (in this case) index_1, index_2 and index_3. I have programmed it is such a way that each page shows there index1_text.
What I want now is to show page_nl in a menu. The code I have now is:
$qh = mysql_query('SELECT id, page_nl FROM tMenu ORDER BY id');
$row = mysql_fetch_array($qh);
$id = 'id';
<? echo $row['page_nl']; $id=="1" ;?>
<? echo $row['page_nl']; $id=="2" ;?>
<? echo $row['page_nl'];?>
In the way it is now it shows only page_nl from id 1, but I want that the next link shows page_nl from id 2. I hope my question is more clear now.
Your question isn't very clear - are you asking for something like this
$sql = "select * from yourtable where id = 1";
$result = mysql_query($sql);
//I am assuming there are more than 1 rows for ID 1
while($row = mysql_fetch_assoc($result)) {
echo $row['page_nl'];
}
OR ============================
$sql = "select * from yourtable"; //Select All
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
if($row['id'] == 1)
{
echo $row['page_nl'];
}
}
Presuming you mean database table, you need a routine to connect to the database then fetch the info:
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "databasename"); // database name
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM table_name"; // put table name here
$result = $mysqli->query($query);
/* numeric array */
/* associative array */
$row = $result->fetch_array(MYSQLI_ASSOC);
printf ("%s (%s)\n", $row["id"], $row["page_nl"]);
/* free result set */
$result->free();
/* close connection */
$mysqli->close();
?>
You need to use a foreach($var as $key =>$value) loop
How do I fetch only one value from a database using PHP?
I tried searching almost everywhere but don't seem to find solution for these
e.g., for what I am trying to do is
"SELECT name FROM TABLE
WHERE UNIQUE_ID=Some unique ID"
how about following php code:
$strSQL = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = mysql_query($strSQL) or die('SQL Error :: '.mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['name'];
I hope it give ur desired name.
Steps:
1.) Prepare SQL Statement.
2.) Query db and store the resultset in a variable
3.) fetch the first row of resultset in next variable
4.) print the desire column
Here's the basic idea from start to finish:
<?php
$db = mysql_connect("mysql.mysite.com", "username", "password");
mysql_select_db("database", $db);
$result = mysql_query("SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID");
$data = mysql_fetch_row($result);
echo $data["name"];
?>
You can fetch one value from the table using this query :
"SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID limit 1"
Notice the use of limit 1 in the query. I hope it helps!!
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT name FROM TABLE WHERE UNIQUE_ID=Some unique ID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();