MySQL SELECT sometimes found nothing even it exists - php

I have PHP script that runs every 3 hours that gets the amazon mws orders and save it into my database.
But before I insert an order into my table, I check first if the order exist
SELECT COUNT(*) total FROM orders WHERE transaction_id = "XXXXXXXXX"
But sometimes even if an order exist, the query will return 0. If return 0, I will insert the order into my table and it will end up duplicating the data.
This instance happens to me in my other PHP scripts and I don't understand the issue.

You should use something called as EXISTS for checking whether a row exists or not in your case order.
SELECT EXISTS(SELECT * FROM table1 WHERE ...);
SELECT EXISTS(SELECT * FROM tableName WHERE condition);

If your database uses master-slave mode,you can try to force the master to query.
You can also use the “INSERT IGNORE INTO orders ....” to ignore duplicate.

You may have an error in your MySQL query. I created a test table and write some code to print the result of the query which is working correctly.
You may not be using the quotations properly as this is the error most
of the time when you are working with queries in PHP
Here is the code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "practise";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_errno());
}
$sql = "SELECT count(*) from test where title='Hello'";
$result = mysqli_query($conn,$sql);
$new =mysqli_fetch_array($result);
echo $new[0];
?>
</body>
</html>
And:
Image of the table where I am executing the query
The output against the MySQL query is:
2
The code works perfectly. If you have any other question, please share your code and I'll be more than happy to help you.

Related

Filtering SQL queries

I'm creating a php query trying to filter from a specific SQL table specific Events.
For example table is called tbl_events and one specific column is showing user ID data let's call it USER_ID
The table has more than 50.000 data lines so if I try and filter it with php it takes TOO much time. So my try is to filter it with SQL before I show the query to the php table and see if it becomes faster.
I want to filter the query in order NOT to show the ones who have an ID let's say "2"
My code is the following (and its obviously not working)
$GetEventsList = GetDataWhere("tbl_events","USER_ID!=2",0);
I'm new in SQL commands so be patient :)
Is this what you're looking for?
Query:
SELECT * FROM tbl_events WHERE USER_ID != '2'
So to implement this with php I would suggest:
$servername = "Your server ip here";
$username = "Database_username_here";
$password = "Database_password_here";
$dbname = "Database_name_here";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM tbl_events WHERE USER_ID != '2'";
// Run $sql content as sql script in db.
$result=$conn->query($sql);

Escape strings/ inserting in php script

I'm trying to finish a script that connects to two databases, each on a different server, and preforms an update. Basically, the tables being selected from and inserted to are identical: I did a dump/import the other day. The script needs to keep my local table up to date from the remote once since there will be daily records inserted into the remote one and I need to keep it up to date locally.
The key here is that I'm determining the new rows on the remote server by looking at the Auto-incremented Primary key that the tables share, SESSIONID . I'm trying to get my loop below to say, if the id exists in remote server and not local, then insert those records in local server.
I run the below script in powershell by typing php 'filename', and I get both of my successful connection messages, and then I get this message: Incorrect datetime value: '' for column 'ALERTINGTIMESTAMP' at row 1. In this record it's trying to insert, the datetime value is NULL, which the table allows for, however I'm worried it's an issue with escaping characters or something.
How can I modify this to escape properly, or get these records inserted.
Note: Replication and large dump/import/table recreations are not an option for us in this situation. We have several similar scripts to this running and we want to keep the same process here. I'm merely looking to resolve these errors or have someone give me a more efficient way of coding this script, perhaps using a max id or something along those lines.
Here's the script:
ini_set('memory_limit', '256M');
// Create connection
$conn = new mysqli($servername, $username, $password);
$conn2 = new mysqli($servername2, $username2, $password2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Check connection2
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
echo "Connected successfully";
$latest_result = $conn2->query("SELECT MAX(`SESSIONID`) FROM `ambition`.`session`");
$latest_row = $latest_result->fetch_row();
$latest_session_id = $latest_row[0];
//Select All rows from the source phone database
$source_data = mysqli_query($conn, "SELECT * FROM `cdrdb`.`session` WHERE `SESSIONID` > $latest_session_id");
// Loop on the results
while($source_item = $source_data->fetch_assoc()) {
// Check if row exists in destination phone database
$row_exists = $conn2->query("SELECT SESSIONID FROM ambition.session WHERE SESSIONID = '".$source_item['SESSIONID']."' ") or die(mysqli_error($conn2));
//if query returns false, rows don't exist with that new ID.
if ($row_exists->num_rows == 0){
//Insert new rows into ambition.session
$conn2->query("INSERT INTO ambition.session (SESSIONID,SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,RESPONSIBLEUSEREXTENSIONID,ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)
VALUES ('".$source['SESSIONID']."' ,
'".$source['SESSIONTYPE']."' ,
'".$source['CALLINGPARTYNO']."' ,
'".$source['FINALLYCALLEDPARTYNO']."',
'".$source['DIALPLANNAME']."',
'".$source['TERMINATIONREASONCODE']."',
'".$source['ISCLEARINGLEGORIGINATING']."',
'".$source['CREATIONTIMESTAMP']."',
'".$source['ALERTINGTIMESTAMP']."',
'".$source['CONNECTTIMESTAMP']."',
'".$source['DISCONNECTTIMESTAMP']."',
'".$source['HOLDTIMESECS']."',
'".$source['LEGTYPE1']."',
'".$source['LEGTYPE2']."',
'".$source['INTERNALPARTYTYPE1']."',
'".$source['INTERNALPARTYTYPE2']."',
'".$source['SERVICETYPEID1']."',
'".$source['SERVICETYPEID2']."',
'".$source['EXTENSIONID1']."',
'".$source['EXTENSIONID2']."',
'".$source['LOCATION1']."',
'".$source['LOCATION2']."',
'".$source['TRUNKGROUPNAME1']."',
'".$source['TRUNKGROUPNAME2']."',
'".$source['SESSIONIDTRANSFEREDFROM']."',
'".$source['SESSIONIDTRANSFEREDTO']."',
'".$source['ISTRANSFERINITIATEDBYLEG1']."',
'".$source['SERVICEEXTENSION1']."',
'".$source['SERVICEEXTENSION2']."',
'".$source['SERVICENAME1']."',
'".$source['SERVICENAME2']."',
'".$source['MISSEDUSERID2']."',
'".$source['ISEMERGENCYCALL']."',
'".$source['NOTABLECALLID']."',
'".$source['RESPONSIBLEUSEREXTENSIONID']."',
'".$source['ORIGINALLYCALLEDPARTYNO']."',
'".$source['ACCOUNTCODE']."',
'".$source['ACCOUNTCLIENT']."',
'".$source['ORIGINATINGLEGID']."',
'".$source['SYSTEMRESTARTNO']."',
'".$source['PATTERN']."',
'".$source['HOLDCOUNT']."',
'".$source['AUXSESSIONTYPE']."',
'".$source['DEVICEID1']."',
'".$source['DEVICEID2']."',
'".$source['ISLEG1ORIGINATING']."',
'".$source['ISLEG2ORIGINATING']."',
'".$source['GLOBALCALLID']."',
'".$source['CADTEMPLATEID']."',
'".$source['CADTEMPLATEID2']."',
'".$source['ts']."',
'".$source['INITIATOR']."',
'".$source['ACCOUNTNAME']."',
'".$source['APPNAME']."',
'".$source['CALLID']."',
'".$source['CHRTYPE']."',
'".$source['CALLERNAME']."',
'".$source['serviceid1']."',
'".$source['serviceid2']."')");
}
}
Like Pankaj said, try something like this:
//Insert new rows into ambition.session
$statement = $conn2->prepare('INSERT INTO ambition.session (SESSIONID,SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO,DIALPLANNAME,TERMINATIONREASONCODE,ISCLEARINGLEGORIGINATING,CREATIONTIMESTAMP,ALERTINGTIMESTAMP,CONNECTTIMESTAMP,DISCONNECTTIMESTAMP,HOLDTIMESECS,LEGTYPE1,LEGTYPE2,INTERNALPARTYTYPE1,INTERNALPARTYTYPE2,SERVICETYPEID1,SERVICETYPEID2,EXTENSIONID1,EXTENSIONID2,LOCATION1,LOCATION2,TRUNKGROUPNAME1,TRUNKGROUPNAME2,SESSIONIDTRANSFEREDFROM,SESSIONIDTRANSFEREDTO,ISTRANSFERINITIATEDBYLEG1,SERVICEEXTENSION1,SERVICEEXTENSION2,SERVICENAME1,SERVICENAME2,MISSEDUSERID2,ISEMERGENCYCALL,NOTABLECALLID,RESPONSIBLEUSEREXTENSIONID,ORIGINALLYCALLEDPARTYNO,ACCOUNTCODE,ACCOUNTCLIENT,ORIGINATINGLEGID,SYSTEMRESTARTNO,PATTERN,HOLDCOUNT,AUXSESSIONTYPE,DEVICEID1,DEVICEID2,ISLEG1ORIGINATING,ISLEG2ORIGINATING,GLOBALCALLID,CADTEMPLATEID,CADTEMPLATEID2,ts,INITIATOR,ACCOUNTNAME,APPNAME,CALLID,CHRTYPE,CALLERNAME,serviceid1,serviceid2)
VALUES (?, ?, ?, ...);');
$statement->bindParam(1, $source['SESSIONID']);
$statement->bindParam(2, $source['SESSIONTYPE']);
$statement->bindParam(3, $source['CALLINGPARTYNO']);
//...
$statement->execute();
You have to use prepare() function to use parameterized query. Here I have taken example of your query with few parameters you can add yourself with other variables.
$stmt = $conn2->prepare("INSERT INTO ambition.session (SESSIONID,SESSIONTYPE,CALLINGPARTYNO,FINALLYCALLEDPARTYNO) VALUES (:SESSIONID ,:SESSIONTYPE ,:CALLINGPARTYNO ,:FINALLYCALLEDPARTYNO)");
$stmt->bindParam(':SESSIONID', $source['SESSIONID']);
$stmt->bindParam(':SESSIONTYPE', $source['SESSIONTYPE']);
$stmt->bindParam(':CALLINGPARTYNO', $source['CALLINGPARTYNO']);
$stmt->bindParam(':FINALLYCALLEDPARTYNO', $source['FINALLYCALLEDPARTYNO']);
$stmt->execute();
You can checkout this link for more understanding. http://php.net/manual/en/mysqli.prepare.php

PHP script, select on server 1 and insert on server 2 if iD doesn't exist (i.e. new records)

We have a phone system database on one server that we cloned/dumped to our local server, but now we need to keep our version updated. Obviously, tables and schema are the same, I just want to run this scheduled script to update with new records that don't exist on the local table (i.e. records that were created since last update).
Below is a test select/insert block. The select query worked on it's own originally, but now I've modified it to use a loop with hopes of using numrows and a foreach to capture everything in the select.
The session table has about 35 columns so I'm looking for the best way to go about this without having to declare every column. I originally tried to do this using update on duplicate key or insert/ignore using a not exists but I don't really know what I'm doing.
Basically, once I select everything, if my table on server 2 doesn't contain a record with the SESSIONID primary key, I want to insert it. I just need some assistance creating this loop script.
Example:
if the table on server 1 has 2 rows with sessionID 12345, and 12346, but my table on server 2 only has up to sessionID 12344, I want to insert the whole records for those two IDs.
//Defining credentials
$servername = "";
$username = "";
$password = "";
$servername2 = "";
$username2 = "";
$password2 = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
$conn2 = new mysqli($servername2, $username2, $password2);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Check connection2
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
echo "Connected successfully";
//Query to select * from Session table on server 1
$query1 = "select * from cdrdb.session";
$results = mysqli_query($conn1, $query1);
foreach ($results as $r => $result) {
$stmt1 = mysqli_prepare($conn2, "insert into ambition.session a where not
exists(a.SESSIONID)");
mysqli_stmt_execute($stmt1) or die(mysqli_error($conn2));
}

Update Mysql with more than one edit

So I run this php script as cron jobs updating points for users on scoreboard.
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE scoreboard SET points='23' WHERE id=2500";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
This works fine for only one id at a time. How can I edit 3 id's with different points each? Thanks.
You don't usually update 3 IDs per query in a list of users for a scoreboard. One request at a time works just fine and including 3 won't make it faster, unless these 3 players all have the same score, but you specifically mentioned you wanted 3 IDs with different scores for each.
If it's about performance/efficiency, use prepared statements (mysqli's prepare) and use a loop after your prepare() in which you:
bind() the parameters (each time for a different user/points)
execute()
If you must.. you could...
update scoreboard
set points = case when ID = 2500 then '23'
when Id = 'XXXX' then 'YY'
when ID = 'YYYY' then 'XX' end
where ID in (2500,'XXXX','YYYY')
But single updates make more sense here. You could write the a bulk insert to a temp table and update from that table if you have a thousands of records to update with different values. This may be faster.

Executing mysqli insert query then immediately selecting ID of new row

I've been spending a couple of hours trying to write mysqli queries to insert a new row in a database (with a primary key ID) and then select the ID of the new row. My code as it currently is:
<?php
include('connectionData.php');
$conn = mysqli_connect($server, $user, $pass, $dbname, $port)
or die('Connection error');
if(isset($_POST['submit'])) {
$pnum = $_POST['pnum'];
$phone_insert_text = "INSERT INTO `voterdatabase`.`phone` (`pnum`) VALUES (?)";
$phone_insert_query = $conn->prepare($phone_insert_text);
$phone_insert_query->bind_param('s', $pnum);
$phone_insert_query->execute();
$phone_select_text = "SELECT phone_id FROM voterdatabase.phone WHERE pnum=?";
$phone_select_query = $conn->prepare($phone_select_text);
$phone_select_query->bind_param('s', $pnum);
$phone_select_query->execute();
$phone_select_query->bind_result($phone_id);
echo $phone_id;
?>
$phone_insert_query executes without issue. But $phone_select_query doesn't appear to run at all, as echo $phone_id; has no effect. What might be going on here? I'm able to run the query directly in MySQLWorkbench.
Note that I previously tried doing this in one query using SELECT LAST_INSERT_ID();, but mysqli fails to execute any query containing that.
Please try this
$lastInsertID= mysqli_insert_id($conn);
Use insert_id property:
<?php
include('connectionData.php');
$conn = mysqli_connect($server, $user, $pass, $dbname, $port)
or die('Connection error');
if(isset($_POST['submit'])) {
$pnum = $_POST['pnum'];
$phone_insert_text = "INSERT INTO `voterdatabase`.`phone` (`pnum`) VALUES (?)";
$phone_insert_query = $conn->prepare($phone_insert_text);
$phone_insert_query->bind_param('s', $pnum);
$phone_insert_query->execute();
$phone_id = $conn->insert_id;
echo $phone_id;
?>
If you wish to be able to use the available functions to get the last inserted id, like mysqli_insert_id(), your table must have an AUTO_INCREMENT column. If not you will not get the id.
Also, even if you have the required columns, this will require two calls. To get around this, what you could do is something like create a stored procedure to do your insert for you and return the inserted id from the procedure.

Categories