escaping mysql table not found - php

I have a script that continuously connects to a database and then truncates table in a loop fashion. The script breaks if there is not table found. How do i escape this to enable it run to the end?
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$username =$row['user_name'];
$url=$row['url'];
//$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
$db = mysql_select_db("ghcomm") ;
mysql_query ("TRUNCATE settings") or die("error settings". mysql_error());
}

Use IF EXISTS in your SQL.
Just replace the last statement :
mysql_query ("TRUNCATE settings") or die("error settings". mysql_error());
with :
mysql_query ("TRUNCATE settings IF EXISTS settings") or die("error settings". mysql_error());
That way you never trigger the die("error settings...") part.
Hope this helps !

Just change
or die("error settings". mysql_error());
to
break;

You have to use the new connection you create. Otherwise the connection from outside the loop will be used all the time:
$db = mysql_select_db("ghcomm", $conn);
mysql_query ("TRUNCATE settings IF EXISTS settings", $conn) or die("error settings". mysql_error($conn));

Related

PHP mysql_query inside FOR only works first loop

I´m trying to update some different registers in a mysql database sending the commands from a FOR loop in php, but the query is only done the 1st loop. Here´s the code:
$conexion = mysql_connect($hostname, $user, $pass) or die ("Error establishing connection with the Database");
mysql_select_db($db,$conexion) or die("Error selecting the Database");
$j=0;
for ($i=0;$i<count($notifs);$i++){
$sql="UPDATE tef SET notif='$notifs[$i]' WHERE sn_rec='$unsersn_recs[$j]';";
echo $sql."<br>";
$res=mysql_query($sql, $conexion) or die (mysql_error());
$j++;
}
mysql_close($conexion);
The query text is correctly done (the echo shows the different lines created), but the changes in the database are done only in the 1st loop (1st query) and I don´t receive any error. What may I be missing?
Thanks in advance!
This is wonderful example where you should use prepared statements.
I give you an example which is also secure against SQL injections.
$mysqli = new mysqli($hostname, $user, $pass, $db);
if (mysqli_connect_errno()) {
die("Error establishing connection!");
}
$stmt = $mysqli->prepare("UPDATE tef SET notif=? WHERE sn_rec=?");
$j=0;
for ($i=0;$i<count($notifs);$i++) {
$stmt->bind_param('ii', $notifs[$i], $unsersn_recs[$j]);
$stmt->execute();
if(!empty($stmt->error)) echo $stmt->error;
$j++;
}
$stmt->close();
$mysqli->close();
Hint: If notif or sn_rec are varchar/text types, just replace the 'i' with a 's' in bind_param().

MYSQL, PHP two connections inside while loop

I have two databases on the same MYSQL server.
I want to be able to query one table on one database, and use the results for an insert into the other table (on the other data base). I've tried moving the mysql_select_db lines around to no avail. Please note this is a one off internal script so security is not a concern (Don't want to us mysqli)
<?php
// Connecting, selecting database
$link1 = mysql_connect('127.0.0.1', 'username', 'password', true)
or die('Could not connect: ' . mysql_error());
$link2 = mysql_connect('127.0.0.1', 'username', 'password', true)
or die('Could not connect: ' . mysql_error());
mysql_select_db('db1', $link1) or die('Could not select database');
mysql_select_db('db2', $link2) or die('Could not select database');
// Performing SQL query
$query = "select fields from table";
$result = mysql_query($query,$link1) or die('Query failed: ' . mysql_error());
while ($row = mysql_fetch_array($result)){
$querynew = "insert into table (blah,blah) values ('$row['name']',$row['name2']')";
mysql_query($querynew, $link2);
}
You can use plain SQL for this to minimize traffic across the wire:
INSERT INTO `db2.tbl1` (`field1`,`field2`)
SELECT `field1`, `field2` FROM `db1.tbl2` WHERE `someCondition`='IsMet'

Trouble inserting data into mysql table with php

I have a few string variables I am trying to insert them into my DB but I am having trouble because nothing is being inserted into the DB. I know the variables are populated. Since all variables are string I'm converting some of them to integers because those fields in the db table are type integer. I tried assigning the mysql_query to a variable and then check to return an error but it didn't display anything. I'm a bit new at PHP so I'm not sure what's wrong with my code below. I appreciate the help.
$connect = mysql_connect("localhost", "user", "pass");
if (!$connect) { die("Could not connect: ". mysql_error()); }
mysql_select_db("dbname");
mysql_query($connect,"INSERT INTO table1 (id, AU, TI, JO, VL, ISS, PB, SN, UR, DO, SP, EP, PY) VALUES ('NULL', '".$authors."', '".$title."', '".$journal."', '".(int)$volume."', '".(int)$issue."', '".$publisher."', '".$serial."', '".$url."', '".$doi."', '".(int)$startpage."', '".(int)$endpage."', '".(int)$year."')");
mysql_close($connect);
Try to debug your code, adding some more useful checks.
$link = mysql_connect("localhost", "user", "pass");
if (!$link) {
die("Could not connect: ". mysql_error());
}
$dbSelected = mysql_select_db("dbname", $link);
if (!$dbSelected) {
die ("Can't select db: " . mysql_error());
}
$result = mysql_query("YOUR_QUERY", $link);
if (!$result) {
die("Invalid query: " . mysql_error());
}
ps: you may want to use mysqly::query, just because mysql_query is deprecated
ps2: you should google about SQL Injection, since your statement doesn't look secure (unless those values are escaped somewhere)
NOTE: I just noticed that you are using a wrong order for the parameters on mysql_query($query, $link). You have put $link as first parameter.

Finding the number of rows of each user in MYSQL

I have databases of users and each has tables. I want to loop through each user and find the number of rows of a particular table common to each. So i connect to the first DB(usersDB) and pick the names of other DB's from a table(userinfo) row(user_name). I then connect to each DB using the names obtained in userinfo and try to find the number of rows they each have on a particular table(products) common to them. I tried this but shows the same number of rows for all of them. Any help??
<?php
//db parameters
$dbhost = "localhost";
$dbname = "usersDB";
$dbuser = "root";
$dbpass = "";
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
//select main db
$query = "SELECT user_name FROM userinfo";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_BOTH))
{
$dbName =$row['user_name'];
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db("dbprefix_".$bName) or die("MySQL Error: " . mysql_error());
// do a query for each db
$query = mysql_query('SELECT * FROM `products`');
$num_rows = mysql_num_rows($query);
echo $dbName." has".$num_rows."products"."<br/>";
}
?>
I think problem is in following line
mysql_select_db("dbprefix_".$bName) or die("MySQL Error: " . mysql_error());
I think this line will be
mysql_select_db("dbprefix_".$dbName) or die("MySQL Error: " . mysql_error());
this may not be your issue but I noticed you arn't closing the connection to each database after you query from it. you should assign a variable to mysql_select_db and after you echo close the database like this:
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
while($row = mysql_fetch_array($result, MYSQL_BOTH)){
$dbName =$row['user_name'];
$db = mysql_select_db("dbprefix_".$dbName, $conn) or die("MySQL Error: " . mysql_error());
if( $db ){
// do a query for each db
$query = mysql_query('SELECT * FROM `products`');
$num_rows = mysql_num_rows($query);
echo $dbName." has".$num_rows."products"."<br/>";
mysql_close( $db );
}
}
also notice I took the mysql_connect() line out of the while loop because you don't need to call this more than once. and I added the $conn variable for your mysql_connect() command, this way you can use $conn in your mysql_select_db() statement. This tell the select_db statement which connection to look in for this database (just alittle more secure).
Seems that there is a typo here:
mysql_select_db("dbprefix_".$bName) or die("MySQL Error: " . mysql_error());
Did you mean "dbprefix_".$dbName instead of $bName?
You don't need to call
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
every time, just call mysql_select_db for each database and PHP will reuse the connection
This is a copy paste from php manual may be it helps you
If you use implode() with the return value by mysql_fetch_array,
if you use MYSQL_BOTH on parameter 2, the result is not really what you're expecting.
For example :
my sql database contains "Amine, Sarah, Mohamed";
$array = mysql_fetch_array($resource,MYSQL_BOTH);
or $array = mysql_fetch_array($resource);
echo implode(" - ", $array);
the result is : Amine-Amine-Sarah-Sarah-Mohamed-Mohamed
and we expect just : Amine-Sarah-Mohamed
You must use MYSQL_NUM or MYSQL_ASSOC on parameter 2 to resolve the problem.
Seems rather inefficient to start up a new connection, using the same user/password for every user you've got. MySQL is perfectly capable of querying across different databases from the same connection:
mysql_connect(...);
$sql = "SELECT user_name FROM userinfo";
$result = mysql_query($sql) or die(mysql_error()) {
while($row = mysql_fetch_assoc($result)) {
$username = $row['user_name'];
$sql2 = "SELECT count(*) AS cnt FROM dbprefix_{$username}.products";
$result2 = mysql_query($sql2) or (die(mysql_error());
echo "$username has {$result2['cnt']} products";
}
In short, doing
SELECT somedb.sometable.somefield
is the same as doing
mysql_select_db('somedb');
SELECT sometable.somefield;

PHP DB Connection questions

I am getting the error:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/mjcrawle/public_html/home/index.php on line 23
Line 23 turns out to be $num_results = mysqli_num_rows($result); but I am thinking the error is further up but I am having trouble finding it.
The actual code that I am using to connect to the DB is (I do understand there is a redundancy if the database cannot connect):
Any help would be wonderful and a reason for the error would be awesome!
/*Connect To DB*/
$conn = mysqli_connect($host, $user, $pwd)
or die("Could not connect: " . mysql_error()); //connect to server
mysqli_select_db($conn, $database)
or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
/*Display Error message if fails*/
echo 'Error, could not connect to the database please try again later.';
exit();
}
/* Query for states */
$query = "SELECT StateAbbreviation, StateName, FROM USState ORDER BY StateName";
$result = mysqli_query($conn, $query);
$num_results = mysqli_num_rows($result);
?>
You have an extra comma before the FROM in query = "SELECT StateAbbreviation, StateName, FROM USState ORDER BY StateName";, you may be getting an error and not having a result when you execute the query.
If the query fails, mysqli_query returns boolean false
After $result = mysqli_query($conn, $query);, you should test the return value before continuing:
if ( ! $result){
$error = mysqli_error($conn);
//do something with the error message
}
See EmCo's answer for why your query is failing.
<?php
$con=mysqli_connect('localhost','root','','dbname') or die ("Connection Failed");
?>
This is the simple method of DB Connection

Categories