I wouldn't want to talk too much, here is my code (I know it is not PDO, but it will once it can work). Almost everything working!!!
Now I am doing the logs and I am stuck! - UPDATE thanks to Michael some of it has fixed!
$statresult=mysql_query($statsql, $actconn) or die(mysql_error());
Optimize function too. This is not working with Multiple DB some reason...
The permission doesn't want to be right I have looked hours and I can't figure it out. A part from that everything works beautifully.
The code reads some rows from the real DB and moves them to the backupDB. But I want a cron job and email alert so I did an easy log (into a table) but it doesn't want to work... I can't even see any error log. Well: PHP Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/sites/stcticketing.org/public_html/back/asu1.php on line 34
<?php
// open db
$dbhost = 'localhost';
$actdbuser = 'user1';
$actdbpass = 'pass';
$bckdbuser = 'user2';
$bckdbpass = 'pass';
$actconn = mysql_connect($dbhost, $actdbuser, $actdbpass) or die ('act Error connecting to mysql');
$bckconn = mysql_connect($dbhost, $bckdbuser, $bckdbpass) or die (' back Error connecting to mysql');
$actdbname = '`web151-tevenyal`';
mysql_select_db($actdbname, $actconn);
$bckdbname = '`web151-bckproba`';
mysql_select_db($bckdbname, $bckconn);
//end opendb
//functions
function test($sqls, $states){
if ($sqls=1){
$resflag=1;
}
else {
$resflag=0;
}
$statsql="INSERT INTO `web151-tevenyal`.`tex_bcklog` (`what`,`how`,`when`) VALUES ('$states',$resflag,CURDATE());";
echo "<p>".$sqls."<br/>".$statsql."</p>";
$statresult=mysql_query($statsql, $actconn) or die(mysql_error());
echo "<p>".$states." - ".$resflag."</p>";
$emaltext=$emailtext.$sqls;
}
function db_rows($db,$ord, $connectdb){
$dbquery="SELECT azon FROM $db ORDER BY azon $ord LIMIT 1";
$dbresult=mysql_query($dbquery, $connectdb);
$row = mysql_fetch_array($dbresult);
$dbrow = $row['azon'];
return $dbrow;
}
// end of functions
//config information...
$acttable = 'adat';
$today = date("yW_Hi");
$newdb = $bckdbname.".test_".$today;
test($permsql, "grant");
test(1, "backupstart");
//creating log table for backup results
$backtablesql="CREATE TABLE IF NOT EXISTS `tex_bcklog` ( `azon` int(11) NOT NULL AUTO_INCREMENT,`what` varchar(255) CHARACTER SET utf8 NOT NULL, `how` varchar(255) CHARACTER SET utf8 NOT NULL, `when` date NOT NULL, PRIMARY KEY (`azon`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;" ;
//$backtableresult=mysql_query($backtablesql);
$firstact= db_rows($actdbname.".".$acttable,"asc", $actconn);
$lastact= db_rows($actdbname.".".$acttable,"desc", $actconn);
$upto=$firstact+25000;
if ($lastact-$firstact>50000) {
//create a new table
$permsql="GRANT SELECT ON `$actdbuser`.* TO `$bckdbuser`#'%' ;";
test($permsql, "grant");
$perm = mysql_query($permsql, $bckconn) or die(mysql_error());
$newdbsql="CREATE TABLE $newdb LIKE $actdbname.`$acttable`";
test($newresult, "createdb");
$newresult = mysql_query($newdbsql, $bckconn) or die(mysql_error());
// copy all the data
$query = "INSERT INTO $newdb SELECT * FROM $actdbname.$acttable WHERE $acttable.azon < $upto";
test($query, "copyrows");
$result = mysql_query($query) or die(mysql_error());
// so what has happened...
$delquery = "DELETE FROM $actdbname.$acttable WHERE $actdbname.$acttable.azon < $upto";
test($delquery, "deleterows");
$delresult = mysql_query($delquery, $actconn);
// then tidy up everything:)
$res = mysql_query('SHOW TABLE STATUS WHERE Data_free / Data_length > 0.1 AND Data_free > 102400', $actconn);
while($optrow = mysql_fetch_assoc($res)) {
mysql_query('OPTIMIZE TABLE ' . $optrow['Name']);
}
}
else {
test(0, "nothing");
}
// send an email to confirm what's happened - thanks:)
// close db
mysql_close($actconn);
mysql_close($bckconn);
?>
Please fix it first and then comment any PDO unless the solution itself:) Any help would be greatly appreciated!
Inside the function that is failing (it is done correctly in the other function db_rows()), your database resource link variables are out of scope. Pass them to the functions as parameters:
For example, pass one in as $connection here:
function test($sqls, $states, $connection){
if ($sqls=1){
$resflag=1;
}
else {
$resflag=0;
}
$statsql="INSERT INTO `web151-tevenyal`.`tex_bcklog` (`what`,`how`,`when`) VALUES ('$states',$resflag,CURDATE());";
echo "<p>".$sqls."<br/>".$statsql."</p>";
$statresult=mysql_query($statsql, $connection) or die(mysql_error());
echo "<p>".$states." - ".$resflag."</p>";
$emaltext=$emailtext.$sqls;
}
Then call the function with the correct connection as in:
test($permsql, "grant", $actconn);
Related
I wrote this php script that allows me to fetch all the rows in a table in my MySQL database.
I have put the echo "1", etc. to see whether it gets to the code at the very end. The output proves it does. However, it does not output anything when echoing json_encode($resultsArray), which I can't seem to figure out why.
Code:
// Create connection
$connection = mysqli_connect("localhost", "xxx", "xxx");
// Check connection
if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } else { echo "0"; }
// select database
if (!mysqli_select_db($connection, "myDB")) { die('Unable to connect to database. '. mysqli_connect_error()); } else { echo "1"; }
$sql = "select * from myTable";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));;
echo "3";
$resultsArray = array();
while($row = mysqli_fetch_assoc($result)) {
// convert to array
$resultsArray[] = $row;
}
echo "4";
// return array w/ contents
echo json_encode($resultsArray);
echo "5";
Output:
01345
I figured, it is not about the json_encode, because I can also try to echo sth. like $result['id'] inside the while loop and it just won't do anything.
For testing, I went into the database using Terminal. I can do select * from myTable without any issues.
Any idea?
After around 20hrs of debugging, I figured out the issue.
As I stated in my question, the code used to work a few hours before posting this question and then suddenly stopped working. #MichaelBerkowski confirmed that the code is functional.
I remembered that at some point, I altered my columns to have a default value of an empty string - I declared them as follows: columnName VARCHAR(50) NOT NULL DEFAULT ''.
I now found that replicating the table and leaving out the NOT NULL DEFAULT '' part makes json_encode() work again, so apparently there's an issue with that.
Thanks to everybody for trying anyway!
I want insert some data to a table of the wordpress then return it's auto increase id value.
I do this but both of these has error:
INSERT INTO wp_sho_app_form (job_id, first_name, last_name) VALUES(1, 'Caldwell', 'Estrada');
SELECT LAST_INSERT_ID();
This code word well in MySql but by $wpdb I get this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'SELECT LAST_INSERT_ID()' at line 1
I call this statement by $wpdb->query and also $wpdb->get_results, but both of them has that error.
I don't want use $wpdb->insert for some reasons and I should use this type of code.
The correct way is to use insert_id.
$lastid = $wpdb->insert_id;
if your make another query its not consistent if you have new entries and a lot of traffic. That can cause wired problems.
And that is only working after insert and you should use them. Don't fight the framework.
You can run a custom query then another to select the last item in the table. If you are using a stand alone php file you need to include the wp-load.php file to get the wordpress functions.
$query = "
INSERT
INTO wp_sho_app_form
(job_id, first_name, last_name)
VALUES
(1, 'Caldwell', 'Estrada')
";
$wpdb->query($query);
$query = "
SELECT *
FROM wp_sho_app_form
ORDER BY col_id desc
LIMIT 1
";
$wpdb->query($query);
There is no way to do multiple query by wpdb. The solution which I could find lastly is using direclty MySqli. I wrote this two function for do it. May be it be useful for sombody. As in ajax wordpress not load so I check to find wp-config fle to get details of connection at first:
public static function run_query($query)
{
$wp_config_path = script_generator::get_wp_config_path();
if($wp_config_path == null){
echo 'Could not found wp_config file!';
return;
}
require_once $wp_config_path;
$mysqli = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result_count = 0;
$result_set = array();
if ($mysqli->multi_query($query)) {
do {
$current_result_count = 0;
$current_result = array();
if ($result = $mysqli->use_result()) {
while ($row = $result->fetch_row()) {
$current_result[$current_result_count] = $row;
$current_result_count++;
}
$result->close();
}
$result_set[$result_count] = $current_result;
if ($mysqli->more_results()) {
$result_count++;
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
return $result_set;
}
function get_wp_config_path(){
$dir = dirname(__FILE__);
do {
if( file_exists($dir."/wp-config.php") ) {
return $dir."/wp-config.php";
}
} while( $dir = realpath("$dir/..") );
return null;
}
I'm having to convert my inspection app to MySQLi but have been having many issues doing so since Amazon EC2 updated their MySQL
With not knowing much about php/mysql to begin with, I'm at a loss. Most of my searches have been way beyond what I understand.
This is what the file used to look like.
<?php
include("connect.php"); // Connect to RDS
$query="SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
$result=mysql_query($query);
$num = mysql_num_rows ($result);
$username = mysql_result($result,$i,"username");
$oldurl = mysql_result($result,$i,"oldurl");
$homedata = mysql_result($result,$i,"homedata");
$clientemail = mysql_result($result,$i,"clientemail");
$general_info = mysql_result($result,$i,"general_info");
$company_name = mysql_result($result,$i,"company_name");
$company_hours = mysql_result($result,$i,"company_hours");
$company_phone = mysql_result($result,$i,"company_phone");
$company_support_email = mysql_result($result,$i,"company_support_email");
$beyondscope = mysql_result($result,$i,"beyondscope");
mysql_close();
?>
This is what I have so far. One error I'm getting line 17 has unexpected ',' (comma), even that every line has the same setup.
Thanks in advance for any help with this.
<?php
include("connect.php"); // Connect to RDS
$query="SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
$result=mysqli_query($GLOBALS["___mysqli_ston"], $query);
$num = mysqli_num_rows($result);
$username = mysqli_fetch_array($result,$i,"username");
$oldurl = mysqli_fetch_array($result,$i,"oldurl");
$homedata = mysqli_fetch_array($result,$i,"homedata");
$clientemail = mysqli_fetch_array($result,$i,"clientemail");
$general_info = mysqli_fetch_array($result,$i,"general_info");
$company_name = mysqli_fetch_array($result,$i,"company_name");
$company_hours = mysqli_fetch_array($result,$i,"company_hours");
$company_phone = mysqli_fetch_array($result,$i,"company_phone");
$company_support_email = ($result,$i, "company_support_email");
$beyondscope = mysqli_fetch_array($result,$i,"beyondscope");
((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
?>
UPDATE: To add connect.php
<?php
$hostname='.rds.amazonaws.com';
$user='username';
$pass='password';
$dbase='dbasename';
$connection = ($GLOBALS["___mysqli_ston"] = mysqli_connect("$hostname" , "$user" , "$pass"))
or die ("Can't connect to MySQL");
$db = ((bool)mysqli_query( $connection, "USE " . $dbase)) or die ("Can't select database.");
?>
I've taken the liberty of rebuilding a bit on how you fetch your values, this should be a bit more easier to read and (in my opinion) a better structure. Also, you can specify the database in your connection, like this (just makes for easier reading, up to you really).
$connection = mysqli_connect($hostname, $user, $pass, $dbase);
if (!$connection) {
echo "An error occurred connecting to the database.";
exit;
}
Below is how your query could look. This will loop through all the results, and put them into the variables, only if we actually have a result.
<?php
include "connect.php"; // Connect to RDS
$query = "SELECT id, username, oldurl, homedata, clientemail, general_info, company_name, company_hours, company_phone, company_support_email, beyondscope FROM inspector WHERE username='{$_SESSION['username']}' ";
if (!$result = mysqli_query($connection, $query)) {
// An error occured, do something
// This means no results could be fetched
}
$num = mysqli_num_rows($result);
if (!$result) { // This means that we only fetch if we have a result
while($row = mysqli_fetch_assoc($result)) {
// Fetching all the rows
$username = $row['username'];
$oldurl = $row['oldurl'];
$homedata = $row['homedata '];
$clientemail = $row['clientemail'];
$general_info = $row['general_info'];
$company_name = $row['company_name'];
$company_hours = $row['company_hours'];
$company_phone = $row['company_phone'];
$company_support_email = $row['company_support_email'];
$beyondscope = $row['beyondscope'];
}
}
?>
JFYI.
There is absolutely no point in converting your inspection app to MySQLi the way it offered in the other answer.
The only point in such a conversion is to make your queries safe while with such a direct conversion it remained congenially vulnerable. So, you might saved yourself a lot of trouble by leaving this code alone, with exactly the same outcome.
Proper way is described in this answer, but you will have to find another volunteer to write a code for you.
To begin with, I am a novice when it comes to PHP and MySQL.
I have a MySQL table called levels that contains two columns: level_id and mapData. Some time ago, I wrote a piece of code using mysql_connect that takes user inputted level_id and fetches the corresponding mapData from the table, and the code works as intended. See below:
<?php
$mysql_host = 'localhost';
$mysql_user = 'username';
$mysql_password = "password";
$mysql_database = 'database';
if (!mysql_connect($mysql_host,$mysql_user,$mysql_password)||!mysql_select_db($mysql_database)){
die('Connection failed');
}
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = mysql_query($query)){
if($query_result = mysql_result($query_run,0,$field)){
return $query_result;
}
}
}
$user_input = mysql_real_escape_string(base64_decode($_GET["level_id"]));
$sql = "SELECT level_id FROM levels WHERE level_id='$user_input'";
$result = mysql_query($sql);
if(mysql_num_rows($result) >0){
$mapData = get_map_data($user_input,'mapData');
print $mapData;
}else{
echo "0";
}
?>
In the case that the user inputs a level_id that does not exist in the database, instead of mapData, he will receive 0. Everything works! I, however, read that mysql_connect is deprecated as of PHP 5.5 and decided to switch from using it in my file to using mysqli:
$conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
After changing to mysqli, my get_map_data function has stopped working. I have made certain that the mysqli connection works, but I am simply hitting my head against the wall in making my function work using it. How do I fix my get_map_data function so that it functions again using mysqli?
You can't mix mysqli and mysql_ functions. Furthermore, your mysqli initialization is creating an object, not a resource. Lastly, there is no mysqli_result() function, so therefore we need to emulate what you're trying to do. You wanted the first row 0 and then wanted a specific $field. Below should be what you want.
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = $mysqli->query($query)){
//no mysqli->result() function, so we need to seek to the row.
$query_run->data_seek(0);
if($query_result = $query_run->fetch_assoc()){
return $query_result[$field];
}
}
}
your get_map_data function currently has query running using mysql_query you have to change that to mysqli_query in order to execute:
function get_map_data($level_id,$field){
$query = "SELECT $field FROM levels WHERE level_id='$level_id'";
if($query_run = mysqli_query($conn,$query)){
if($query_result = mysqli_result($query_run,0,$field)){
return $query_result;
}
}
}
I have done a fair bit of research into what i want to do, although i haven't found anything. I am not too sure if i am looking for the right thing :( I am also a little bit new to PHP and MySQL syntax, so please be kind.
I wish to perform the following in this order:
Connect to a database (DONE)
Query for a specific string (I think im done)
From here is gets a bit fuzzy :(
If a match is found for the variable, copy the whole row (I need other variables).
Assign the values from the SQL query to a PHP variables.
From there i will be right to carry on.
I have established the connection to the database with the following:
function connect() {
$dbname = 'database';
$dbuser = 'username';
$dbpass = 'password';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
}
And then calling the function connect();
I then wish to query the database for a particular value, for the sake of this argument i will use a static value. This is what i have:
mysql_select_db(DATABASENAME) or die( "Unable to select database");
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'";
$result=mysql_query($query);
From here i am not too sure how to compare the query result to see if it is a match (something along the lines of mysql rows?).
If there is a match, then i would like to obtain the entire row, and assign each value to a php variable.
I am not asking for you to do it for me, simply i kick in the right direction should be fine!
Hope it explains it enough :)
Thanks for your kind guidance
Ok. You will want to keep the connection to the mysql database somewhere. A common use is $conn.
So you would have
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
Then, either from the URL or Post, or just some variables you have sitting in your php file, you can query the database by putting the variables in the query itself. Also, here you can use $conn so that you have one place to connect to the database, in an include for example, and you won't have to make all of the connection string in each place you need to connect to the DB.
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%" . $varToCompare . "%'";
$result=mysql_query($query,$conn);
Above you are using a like. You may want to just look at doing .. Where column=$var.
Then you can use php to spin through the results into an array (for queries where would get multiple rows).
Where the hell you learned how to use MySQL in PHP ? The mysql_* functions are more then 10 years old and not maintained anymore. Community has already begun to work on deprecating them.
You should be using PDO or MySQLi for that.
// connection to database
$db = new PDO('mysql:host=localhost;dbname=datadump_pwmgr;charset=UTF-8',
'datadump_pwmgr',
'kzddim05xrgl');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// setting up prepared statement for the query
$statement = $db->prepare('SELECT * FROM table WHERE column LIKE :value');
$statement->bindParam(':value', $some_variable, PDO::PARAM_STR, 127);
// executing query and fetching first result
if ( $statement->execute())
{
$data = $statement->fetch(PDO::FETCH_OBJ);
var_dump( $data );
}
This should give you something like what you needed. Though, I would recommend to try this tutorial. And learning more about prepared statements could be useful too.
Also , if you are working with objects, then it is possible to create a single DB connection object , and pass it to multiple other classes to use it:
$pdo = new PDO('sqlite::memory:');
$a = new Foo( $pdo );
$b = new Bar( $pdo, 'something');
This way you pass both objects the same database connection, and you do not need to reinitialize it.
I think you're looking for something like this:
$count = mysql_num_rows($result);
//if there is more then 1 record retrieved from the database
if($count > 0)
{
//Do what ever you want to do here, which I think you want to be
while ($row = mysql_fetch_assoc($result))
{
echo $row["Columnname1"];
echo $row["Columnname2"];
echo $row["Columnname3"];
}
}
else
{
echo "There are no matches for this specific value";
}
You can get the queried data by rows as an associated array using mysql_fetch_array():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_array($data)) !== false)
{
echo "row = $row, name1 = " . $result["name1"] . ", name2 = " . $result["name2"];
$row ++;
}
... or as an objects using mysql_fetch_object():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_object($data)) !== false)
{
echo "row = $row, name1 = $result->name1, name2 = $result->name2";
$row ++;
}
I'm not too sure of what you want, but I can see one probable bug here: you're using LIKE in a way which means =: in order to have LIKE to behave like a like, you need some joker chars :
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'" // This will return all rows where column='VAUL'
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'" // This will return all rows where column='%VAUL%' // This will return any row containing 'VAUL' in column
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE'" // This will return all rows where column='%VAUL' // this will return all rows ending by VAUL. I guess you get it now :)
An to retrieve the actual results:
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'";
$result=mysql_query($query);
while (false !== ($row = mysql_fetch_assoc($result))) {
//here $row is an array containing all the data from your mysql row
}
Try to write the database connection in another page no need to use function and include that page in where ever you need.
ex: require_once 'dbConnect.php';
dbConnect.php consists:
<?php
$dbname = 'datadump_pwmgr';
$dbuser = 'datadump_pwmgr';
$dbpass = 'kzddim05xrgl';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
?>